Thursday, 26 June 2014

C++ program to rotate an array left/right by n places

Here are C++ program to rotate an array left/right by n places. First program rotate an left by n places and second program rotate an array right by n places.


C++ program to rotate an array right by n places
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,n,temp;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements : ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    cout<<"Enter value of n : ";
    cin>>n;
    for(int i=0;i<n;i++)
    {
        temp=a[0];
        for(int y=0;y<num-1;y++)
            a[y]=a[y+1];
        a[num-1]=temp;
    }
    cout<<"After Rotating "<<n<<" places right : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}

OUTPUT




C++ program to rotate an array left by n places
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,n,temp;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements : ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    cout<<"Enter value of n : ";
    cin>>n;
    for(int i=0;i<n;i++)
    {
        temp=a[num-1];
        for(int y=num-1;y>0;y--)
            a[y]=a[y-1];
        a[0]=temp;
    }
    cout<<"After Rotating "<<n<<" places Left : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}

OUTPUT




No comments:

Post a Comment