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. This C example allows the user to enter the array size, array items, and the number of times the array has to rotate towards the right side. Next, we used nested for loop to shift the array 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 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);
    
    rightRotateArray(a, size, num);
    
    printf("\nArray Elements After Right Rotating Array  =  ");
    PrintArray(a, size);
    return 0;
}
Please Enter Size of the  Rotate Array = 7
Please Enter the Rotate Array Elements = 10 20 30 40 50 60 70
Number of Times Right Rotate an Array = 5

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