C++ Program to reverse array

Simple C program to reverse array: In this programming we are swapping array elements. For example we are swapping first element with last element, second element with second last element and so on.
 
/* C++ program to reverse array */
#include<iostream>
using namespace std;
int main()
{
 int arr[]={12,43,23,45,43,32,10,45};
 /* size of array is n */
 int i,j,n=sizeof(arr)/sizeof(arr[0]);
 for(i=0,j=n-1;i<j;i++,j--)
 {
  int temp=arr[i];
  arr[i]=arr[j];
  arr[j]=temp;
 }
 cout<<"Reverse array : "<<endl;
 for(i=0;i<n;i++)
 {
  cout<<arr[i]<<" ";
 }
 cout<<endl;
 return 0;
}
/* End of the program */
 

Another C++ program to reverse array using pointer
 
/* C++ program to reverse array */
#include<iostream>
using namespace std;
int main()
{
 int arr[]={12,43,23,45,43,32,10,45};
 /* size of array is n */
 int *ptr,n=sizeof(arr)/sizeof(arr[0]);
 /* Sotre address of first element into ptr */
 ptr=arr;
 /* Set ptr to last element */
 for(int i=1;i<n;i++)
 {
  ptr++;
 }
 cout<<"Reverse array : "<<endl;
 for(;ptr>=arr;ptr--)
 {
  cout<<*ptr<<" ";
 }
 cout<<endl;
 return 0;
}
/* End of the program */
 
C++ program to reverse array using while loop
 
/* C++ program to reverse array */
#include<iostream>
using namespace std;
int main()
{
 int arr[]={32,17,65,97,63,120,65,23};
 /* size of array is n */
 int n=sizeof(arr)/sizeof(arr[0]);
 int i=0,j=n-1;
 while(i<j)
 {
  int temp=arr[i];
  arr[i]=arr[j];
  arr[j]=temp;
  i++;
  j--;
 }
 cout<<"Reverse array : "<<endl;
 for(i=0;i<n;i++)
 {
  cout<<arr[i]<<" ";
 }
 cout<<endl;
 return 0;
}
/* End of the program */





Popular posts from this blog