w3resource

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

C-programming basic algorithm: Exercise-37 with Solution

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

C Programming Code Editor:

Previous: Write a C program to compute the sum of the elements of an given array of integers.
Next: Write a C program to reverse a given array of integers and length 5.

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.