C Program for Array Rotation



Write a C program to left rotate an array by n position. How to rotate left rotate an array n times in C programming. Logic to rotate an array to left by n position in C program.

Input: arr[]=1 2 3 4 5 6 7 8 9 10
N=3
Output: 4 5 6 7 8 9 10 1 2 3

Explanation

  • Read elements in an array say arr.

  • Read number of times to rotate in some variable say N.

  • Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last.

Example

#include <iostream>
using namespace std;
int main() {
 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 int i, N, len, j;
 N=3;
 len=10;
 int temp=0;
 for (i = 0; i < N; i++) {
int x = arr[0];
for (j = 0; j < len; j++) {
 temp=arr[j];
 arr[j] = arr[j + 1];
 arr[j+1]=temp;
}
arr[len - 1] = x;
 }
 for (i = 0; i < len; i++) {
cout<< arr[i]<<"\t";
 }
}
Updated on: 2024-12-26T11:15:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements