Home  >  Article  >  Backend Development  >  C program for array rotation?

C program for array rotation?

PHPz
PHPzforward
2023-08-30 10:17:051103browse

Write a C program to rotate an array to the left by n positions. How to left rotate an array n times in C programming. Implement the logic of rotating an array left by n positions in a C program.

C program for array rotation?

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 the elements in the array, called arr.

  • Read the number of rotations into a variable N.

  • Rotate the given array left once and repeat N times. Effectively, left rotation moves the array elements one position to the left and copies the first element to the last position.

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";
   }
}

The above is the detailed content of C program for array rotation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete