Thursday 26 June 2014

C++ program to reverse an array

Here are four different C++ programs to reverse an array using third array, using swapping, using pointers and fourth program to print reverse of an array using recursion.


Method 1 : C++ program to reverse an array using third array
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,temp[20];
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements of array : ";
    for(int i=0;i<num;i++)
        cin>>a[i];
    for(int i=num-1;i>=0;i--)
         temp[i]=a[num-i-1];
    for(int i=0;i<num;i++)
        a[i]=temp[i];
    cout<<"After reversing the array : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}



Method 1 : C++ program to reverse an array using swapping
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,mid,temp;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements of array : ";
    for(int i=0;i<num;i++)
        cin>>a[i];
    mid=num/2;
    for(int i=0,y=num-1;i<mid;i++,y--)
    {
        temp=a[i];
        a[i]=a[y];
        a[y]=temp;
    }
    cout<<"After reversing the array : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}



Method 1 : C++ program to reverse an array using pointers
#include<iostream>
using namespace std;
int main()
{
    int *p,n,*q,temp,*temp1;
    cout<<"How many elements to be entered : ";
    cin>>n;
    p=new int[n];
    temp1=p;
    cout<<"Enter elements : ";
    for(int i=0;i<n;i++)
        cin>>p[i];
    q=&p[n-1];
    while(q>=p)
    {
        temp=*p;
        *p=*q;
        *q=temp;
        p++,q--;
    }
    cout<<"Reverse of array : ";
    for(int i=0;i<n;i++)
        cout<<temp1[i]<<" ";
    return 0;
}



Method 1 : C++ program to print reverse of an array using recursion
#include<iostream>
using namespace std;
void rearr(int *a,int i,int num)
{
    if(i==num)
        return ;
    else
        rearr(a,i+1,num);
    cout<<a[i]<<" ";
}
int main()
{
    int a[20],num;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements of array : ";
    for(int i=0;i<num;i++)
        cin>>a[i];
    cout<<"Reverse of array : ";
    rearr(a,0,num);
    return 0;
}




No comments:

Post a Comment