Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C Program To Sort 2D Array Across Rows
Next article icon

C Program for Program for array rotation

Last Updated : 17 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. 
 

Array

Rotation of the above array by 2 will make array

ArrayRotation1

Recommended PracticeRotate ArrayTry It!

Method 1 (Rotate one by one):

leftRotate(arr[], d, n)
start
For i = 0 to i < d
Left rotate all elements of arr[] by one
end

To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] …and finally temp to arr[n-1]
Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 
Rotate arr[] by one 2 times 
We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation.

Below is the implementation of the above approach :

C
// C++ program to illustrate how to rotate array #include <stdio.h>  // Function to rotate array left by one position void leftRotateByOne(int arr[], int n) {     int temp = arr[0];     for (int i = 0; i < n - 1; i++) {         arr[i] = arr[i + 1];     }     arr[n - 1] = temp; }  // Function to rotate array left by d positions void leftRotate(int arr[], int d, int n) {     for (int i = 0; i < d; i++) {         leftRotateByOne(arr, n);     } }  // Function to print an array void printArray(int arr[], int n) {     for (int i = 0; i < n; i++) {         printf("%d ", arr[i]);     }     printf("\n"); }  int main() {     int arr[] = { 1, 2, 3, 4, 5, 6, 7 };     int n = sizeof(arr) / sizeof(arr[0]);     int d = 2;      // Rotate array left by d positions     leftRotate(arr, d, n);      printf("Array  after rotated by %d positions is: ", d);     printArray(arr, n);      return 0; } 

Output
Array  after rotated by 2 positions is: 3 4 5 6 7 1 2  


Method 2 (A Juggling Algorithm) :

This is an extension of method 2. Instead of moving one by one, divide the array in different sets 
where number of sets is equal to GCD of n and d and move the elements within sets. 
If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.
Here is an example for n =12 and d = 3. GCD is 3 and

Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
a) Elements are first moved in first set – (See below
diagram for this movement)

      arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}

b) Then in second set.
arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}

c) Finally in third set.
arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}

Below is the implementation of the above approach :

C
// C program to rotate an array by // d elements #include <stdio.h>  /* function to print an array */ void printArray(int arr[], int size);  /*Function to get gcd of a and b*/ int gcd(int a, int b);  /*Function to left rotate arr[] of size n by d*/ void leftRotate(int arr[], int d, int n) {     int i, j, k, temp;     /* To handle if d >= n */     d = d % n;     int g_c_d = gcd(d, n);     for (i = 0; i < g_c_d; i++) {         /* move i-th values of blocks */         temp = arr[i];         j = i;         while (1) {             k = j + d;             if (k >= n)                 k = k - n;             if (k == i)                 break;             arr[j] = arr[k];             j = k;         }         arr[j] = temp;     } }  /*UTILITY FUNCTIONS*/ /* function to print an array */ void printArray(int arr[], int n) {     int i;     for (i = 0; i < n; i++)         printf("%d ", arr[i]); }  /*Function to get gcd of a and b*/ int gcd(int a, int b) {     if (b == 0)         return a;     else         return gcd(b, a % b); }  /* Driver program to test above functions */ int main() {     int arr[] = { 1, 2, 3, 4, 5, 6, 7 };     leftRotate(arr, 2, 7);     printArray(arr, 7);     getchar();     return 0; } 

Output
3 4 5 6 7 1 2 

Output : 

3 4 5 6 7 1 2 

Time complexity : O(n) 
Auxiliary Space : O(1)



Next Article
C Program To Sort 2D Array Across Rows
author
kartik
Improve
Article Tags :
  • C Programs

Similar Reads

  • C Program for Reversal algorithm for array rotation
    Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example: Input: arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output: arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Algorithm : rotate(arr[], d, n) reverse(arr[], 1, d) ; reverse(arr[], d + 1, n);
    3 min read
  • C Program for Program to cyclically rotate an array by one
    Given an array, cyclically rotate the array clockwise by one. Examples: Input : arr[] = {1, 2, 3, 4, 5} Output : arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. C/C++ Code // C++ code for program to // cyclically rotate an array by one # inc
    2 min read
  • C Program for Pancake sorting
    Given an unsorted array, sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i C/C++ Code /* C program for Pancake Sorting */ #include <stdio.h> #include <stdlib.h> /* Reverses arr[0..i] */ void flip(int arr[], int i) { int
    2 min read
  • C Program To Sort 2D Array Across Rows
    Here, we will see how to sort the 2D Array across rows using a C program: Input: 8 5 7 2 7 3 0 1 8 5 3 2 9 4 2 1 Output: 2 5 7 8 0 1 3 7 2 3 5 8 1 2 4 9Approach: In this approach, we use Bubble Sort. First Start iterating through each row of the given 2D array, and sort elements of each row using th
    2 min read
  • C Program to Sort an Array in Ascending Order
    Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element. The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example:
    3 min read
  • C Program For Printing 180 Degree Rotation of Simple Half Left Pyramid
    The 180° Rotation of a Simple Half Left Pyramid is a pattern where the base of the pyramid is aligned with the bottom, and the entire structure appears rotated by 180°. The resulting structure is nothing but inverted right half pyramid. In this article, we will learn how to print the 180° Rotated Ha
    2 min read
  • C Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put ba
    2 min read
  • C Program For Printing Inverted Pyramid
    An Inverted Pyramids are inverted triangular patterns where the base is at the top, and the rows decrease in size as they move downwards. In this article, we will learn how to print different types of inverted pyramid patterns using C program. There can be 3 types of inverted pyramid patterns: Inver
    7 min read
  • C Program for Turn an image by 90 degree
    Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser and try your solution before going further. An image can be treated as 2D matrix which can be stored in a buffer. We are provided with matrix dimensions and it's base address. How can we turn it? For example s
    4 min read
  • C Program to Traverse an Array
    Write a C program to traverse the given array that contains N number of elements. Examples Input: arr[] = {2, -1, 5, 6, 0, -3} Output: 2 -1 5 6 0 -3 Input: arr[] = {4, 0, -2, -9, -7, 1} Output: 4 0 -2 -9 -7 1 Different Ways to Traverse an Array in CArrays are versatile data structures and C language
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences