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

C program for array rotation?

PHPz
Release: 2023-08-30 10:17:05
forward
1151 people have browsed it

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
Copy after login

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";
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template