Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Circular rotation of an array by K positions

Circular Rotation of an Array by K Position

In this article, we will brief in on how to perform circular rotation  on an array in C programming. In circular rotation we will rotate the elements in the array where one rotation operation moves the last element of the array to the first position and shifts all remaining elements to the right.

Algorithm

  • Declare and initialize the array
  • Enter index value for circular rotation
  • Perform circular rotation
  • Now using two for loops and a temp variable for  circular rotation
  • Store last element of the array in temp variable
  • Using second loop start shifting the elements of  the array  by one
  • Than last element of the array will be added to the starting of the array
  • Than display the array at the end.

C Code Based on above algorithm

#include        
int main()
{
int size;
printf("Size of array: ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements ");
for(int a=0;a<size;a++)
scanf("%d",&arr[a]);
int n;
printf("Enter the index from where you want your array to rotate ");
scanf("%d",&n);
printf("Array: \n");
for (int a = 0; a < size; a++) {
printf("%d ", arr[a]);
}
for(int a = 0; a < n; a++)
{
int b, temporary;
temporary = arr[size-1];
for(b = size-1; b > 0; b--)
{
arr[b] = arr[b-1];
}
arr[0] = temporary;
}
printf("\n");
printf("New Array: \n");
for(int a = 0; a< size; a++){
printf("%d ", arr[a]);
}
return 0;
}
Input

Size of array: 6
Enter the elements 2 3 4 5 6 7
Enter the index from where you want your array to rotate 3

Output
Array:
2 3 4 5 6 7
New Array:
5 6 7 2 3 4