0
4.8kviews
Write a program in C to cyclically rotate the elements in array.

Program should accept a choice in which direction to rotate i.e. left or right. Depending on choice it should perform cyclic rotation. Suppose array A contains elements {1, 2, 3, 4, 5} then if choice is rotate right o/p should be {5, 1, 2, 3, 4) and if choice is rotate left then o/p should be (2, 3, 4, 5, 1)

1 Answer
0
164views

Program:

#include<stdio.h>
#include<conio.h>
int main(){
    int n, i, a[100], b[100];
    int choice, temp;
    printf("Enter the number of elements:");
    scanf("%d", &n);    
    for(i=0; i<=n-1; i++)   {
        printf("Enter a value:");
        scanf("%d", &a[i]);
}
    printf("1. Rotate right\n2. Rotate left\n\nEnter your choice:");
    scanf("%d", &choice);
    switch(choice)  {
        case 1: temp = a[n-1];
        for(i=n-1; i>=1; i--)   {
a[i]=a[i-1];
        }
        a[0]=temp;
        printf("The new array is:\n");

for(i=0; i<=n-1; i++)   {
            printf("%d\n", a[i]);
        }

        case 2: temp = a[0];
        for(i=0; i<n-1; i++)    {
a[i]=a[i+1];
        }
            a[n-1]=temp;
            printf("The new array is:\n");
            for(i=0; i<=n-1; i++)   {
                printf("%d\n", a[i]);
            }   
    }//switch ends
    getch();    
}//main ends

Output:

Enter the number of elements: 5

Enter a value: 1 2 3 4 5

  • Rotate right
  • Rotate left

Enter your choice: 2

The new array is: 2 3 4 5 1

Please log in to add an answer.