w3resource

C Exercises: Rotate the elements of a given array of integers in left direction and return the new array


37. Left Rotate Array

Write a C program to rotate the elements of a given array of integers (length 4 ) in the left direction and return the updated array.

C Code:

#include <stdio.h>
#include <stdlib.h>

// Function prototype for 'print_array'
void print_array(int parray[], int size);

int main(void){ 
    // Declaration and initialization of variables
    int arr_size;
    int a1[] = {10, 20, 30, 40};

    // Calculating the size of the array
    arr_size = sizeof(a1)/sizeof(a1[0]);

    // Printing the original array
    printf("Elements in original array are: ");  
    print_array(a1, arr_size);

    // Creating a new array by rearranging elements from the original array
    int result[] = { a1[1], a1[2], a1[3], a1[0] };

    // Calculating the size of the new array
    arr_size = sizeof(result)/sizeof(result[0]);

    // Printing the new array
    printf("\nElements in new array are: ");  
    print_array(result, arr_size);
}     

// Definition of the 'print_array' function
void print_array(int parray[], int size)
{
    int i;      
    for( i=0; i<size-1; i++)  
    {  
        // Printing each element with a comma and a space
        printf("%d, ", parray[i]);  
    } 
    // Printing the last element without a comma and space
    printf("%d ", parray[i]);  
    // Printing a new line to separate the elements
    printf("\n");   
}

Sample Output:

Elements in original array are: 10, 20, 30, 40 

Elements in new array are: 20, 30, 40, 10 

Pictorial Presentation:

C Programming Algorithm: Rotate the elemets of a given array of integers (length 4 ) in left direction and return the new array

Flowchart:

C Programming Algorithm Flowchart: Rotate the elemets of a given array of integers (length 4 ) in left direction and return the new array

For more Practice: Solve these Related Problems:

  • Write a C program to rotate the elements of an array to the right by one position.
  • Write a C program to rotate an array by n positions to the left.
  • Write a C program to perform a cyclic rotation on an array such that the last element becomes the first.
  • Write a C program to rotate an array of integers based on a user-defined pivot index.

Go to:


PREV : Sum Array Elements.
NEXT : Reverse Array.

C Programming Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.