C program to shift elements of an array in the right direction

C program to shift elements of a single dimensional array in the right direction by one position

This C program is to shift the elements of a single dimensional array in the right direction by one position.For example, if an array a consists of elements a={1,2,3}, then on shifting these elements towards the right direction we would get a={3,1,2}.

 Logic

We store the last element in the temp variable and then put it in the starting position i.e. a[0] and the remaining elements we shift it towards the right by one position by storing the element in the current position to the next position.

Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 3

Let us take elements for array a={1,2,3}.

temp=a[n-1];  i.e. temp=[3-1] i.e. temp=a[2] i.e. temp=3;

1st iteration  for(i=n-1;i>0;i–)  i.e. for(i=3-1;i>0;i–) i.e.  for(i=2;2>0;i–)

a[i]=a[i-1];  i.e. a[2]=a[2-1] i.e. a[2]=a[1] i.e. a[2]=2

2nd iteration  for(i=n-1;i>0;i–)  i.e. for(i=1;1>0;i–)

a[i]=a[i-1];  i.e. a[1]=a[1-1] i.e. a[2]=a[0] i.e. a[1]=1

As i(0) is not greater than 0 we come out of the for loop.

a[0]=temp i.e. a[0]=3

Hence we have shifted the elements of an array in the right direction by one position and our final output is a={3,1,2}.

Program

#include<stdio.h>

void  main()
{
  int i,n,a[100],temp;

    printf("Enter the number of elements:\n") ;
    scanf("%d",&n);
 
    printf("Enter the elements\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
 
    printf("Original array\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
 
    /* shifting array elements */
    temp=a[n-1];
    for(i=n-1;i>0;i--)
    {
        a[i]=a[i-1];
    }
    a[0]=temp;
 
    printf("\nNew array after rotating by one postion in the right direction\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
}

Output

Share Me!