C program to left rotate an array

Write a C program to left rotate an array by n position. Logic to rotate an array to left 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 left rotation: 4 5 6 7 8 9 10 1 2 3

Required knowledge

Basic C programming, Loop, Array, Function

Logic to left rotate an array

Below is the step by step descriptive logic to left rotate an array.

  1. Read elements in an array say arr.
  2. Read number of times to rotate in some variable say N.
  3. Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last.

Algorithm to left rotate an array
Begin:
    read(arr)
    read(n)
    For i←1 to n do
        rotateArrayByOne(arr)
    End for
End
rotateArrayByOne(arr[], SIZE)
Begin:
    firstarr[0]
    For i←1 to SIZE - 1 do
        arr[i] ← arr[i + 1]
    End for
    arr[SIZE - 1] ← first
End

Program to left rotate an array

/**
 * C program to left 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 left 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, first;

    /* Store first element of array */
    first = arr[0];

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

    /* Copies the first element of array to last */
    arr[SIZE-1] = first;
}


/**
 * 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 left rotate: 3
Array before rotation
1 2 3 4 5 6 7 8 9 10

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

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