C Program to Right Rotate Array Elements

Write a C program to right rotate array elements for a given number of times using a for loop and functions.

C Program to Right Rotate Array Elements using for loop

This example allows the user to enter the size, items, and the number of times the array has to rotate toward the right side. Next, we used a nested for loop to shift the array of items places with the help of a temp variable.

#include<stdio.h>

void PrintArray(int a[], int Size) 
{		
 	for(int i = 0; i < Size; i++)  	
    {
        printf("%d  ", a[i]);
    }
    printf("\n");
} 

int main()
{
    int size, i, j, a[10], num, temp;

    printf("Please Enter Size of the Rotate Array = ");
    scanf("%d", &size);

    printf("Please Enter the Rotate Array Elements = ");
    for(i = 0; i < size; i++) {
        scanf("%d", &a[i]);
    }
    
    printf("Number of Times Right Rotate an Array = ");
    scanf("%d", &num);

    for(i = 0; i < num; i++) 
    {
        temp = a[size - 1];
        for(j = size - 1; j > 0; j--)
        {
            a[j] = a[j - 1];
        }
        a[j] = temp;
    }
    
    printf("\nArray Elements After Right Rotating Array  :  ");
    PrintArray(a, size);
}
C Program to Right Rotate Array Elements

This C program rotates array elements for a given number of times on the right hand side using functions.

#include<stdio.h>

void PrintArray(int a[], int Size) 
{		
 	for(int i = 0; i < Size; i++)  	
    {
        printf("%d  ", a[i]);
    }
    printf("\n");
} 

void rightRotateArray(int a[], int size, int num)
{
    int i, j, temp;

    for(i = 0; i < num; i++) 
    {
        temp = a[size - 1];
        for(j = size - 1; j > 0; j--)
        {
            a[j] = a[j - 1];
        }
        a[j] = temp;
    }
}

int main()
{
    int size, i, a[10], num, temp;

    printf("Please Enter Size = ");
    scanf("%d", &size);

    printf("Please Enter the Elements = ");
    for(i = 0; i < size; i++) {
        scanf("%d", &a[i]);
    }
    
    printf("Number of Times Right Rotate an Array = ");
    scanf("%d", &num);
    
    rightRotateArray(a, size, num);
    
    printf("\nElements After Right Rotating Array  =  ");
    PrintArray(a, size);
    return 0;
}
Please Enter Size = 7
Please Enter the Elements = 10 20 30 40 50 60 70
Number of Times Right Rotate an Array = 5

Elements After Right Rotating Array  =  30  40  50  60  70  10  20