C program to right rotate an array

Write a C program to right rotate an array by n position. Logic to rotate an array to right by n position in C program.

Example

Input

Input 10 elements in array: 1 2 3 4 5 6 7 8 9 10
Input number of times to rotate: 3

Output

Array after right rotation: 8 9 10 1 2 3 4 5 6 7

Required knowledge

Basic C programming, Loop, Array, Function

Logic to right rotate an array

Below is the step by step descriptive logic to rotate an array to right by n positions.

  1. Read elements in an array say arr.
  2. Read number of times to rotate in some variable say N.
  3. Right rotate the given array by 1 for N times. In real right rotation is shifting of array elements to one position right and copying last element to first.
Algorithm to right rotate an array
Begin:
    read(arr)
    read(n)
    For i←1 to n do
        rotateArrayByOne(arr)
    End for
End
rotateArrayByOne(arr[], SIZE)
Begin:
    lastarr[SIZE - 1]
    For iSIZE-1 to 0 do
        arr[i] ← arr[i - 1]
    End for
    arr[0] ← last
End

Program to right rotate an array

/**
 * C program to right rotate an array
 */

#include <stdio.h>
#define SIZE 10 /* Size of the array */

void printArray(int arr[]);
void rotateByOne(int arr[]);


int main()
{
    int i, N;
    int arr[SIZE];

    printf("Enter 10 elements array: ");
    for(i=0; i<SIZE; i++)
    {
        scanf("%d", &arr[i]);
    }
    printf("Enter number of times to right rotate: ");
    scanf("%d", &N);

    /* Actual rotation */
    N = N % SIZE;

    /* Print array before rotation */
    printf("Array before rotation\n");
    printArray(arr);

    /* Rotate array n times */
    for(i=1; i<=N; i++)
    {
        rotateByOne(arr);
    }

    /* Print array after rotation */
    printf("\n\nArray after rotation\n");
    printArray(arr);

    return 0;
}


void rotateByOne(int arr[])
{
    int i, last;

    /* Store last element of array */
    last = arr[SIZE - 1];

    for(i=SIZE-1; i>0; i--)
    {
        /* Move each array element to its right */
        arr[i] = arr[i - 1];
    }

    /* Copy last element of array to first */
    arr[0] = last;
}


/**
 * Print the given array
 */
void printArray(int arr[])
{
    int i;

    for(i=0; i<SIZE; i++)
    {
        printf("%d ", arr[i]);
    }
}
Output
Enter 10 elements array: 1 2 3 4 5 6 7 8 9 10
Enter number of times to right rotate: 3
Array before rotation
1 2 3 4 5 6 7 8 9 10

Array after rotation
8 9 10 1 2 3 4 5 6 7

Happy coding ;)

Recommended posts

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment