codescracker


c++

C++ Program to Reverse Array



« Previous Program Next Program »


Reverse Array in C++

To reverse an array in C++ programming, you have to ask to the user to enter the array size and array elements. Now start swapping the array elements. Make a variable say temp of same type. Place first element in the temp, then last element in the first, then temp in the last and continue to reverse the array and print the reversed array on the screen as shown here in the following program.

C++ Programming Code to Reverse Array

Following C++ program ask to the user to enter the size of the array then ask to enter the array elements to reverse the array, then display the reverse of the array on the screen:

/* C++ Program - Reverse Array */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int arr[50], size, i, j, temp;
	cout<<"Enter array size : ";
	cin>>size;
	cout<<"Enter array elements : ";
	for(i=0; i<size; i++)
	{
		cin>>arr[i];
	}
	j=i-1;  // now j will point to the last element
	i=0;   //  and i will be point to the first element
	while(i<j)
	{
		temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
		i++;
		j--;
	}
	cout<<"Now the Reverse of the Array is : \n";
	for(i=0; i<size; i++)
	{
		cout<<arr[i]<<" ";
	}
	getch();
}

When the above C++ program is compile and executed, it will produce the following output:

C++ program to reverse array

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test