Write a C program to left rotate array items for a given number of times using a for loop. This C example allows the user to enter the number of times the array has to left rotate, size, and elements.
#include<stdio.h> void PrintArray(int a[], int Size) { for(int i = 0; i < Size; i++) { printf("%d ", a[i]); } } int main() { int Size, i, j, num, temp; printf("Please Enter the Size of an Array = "); scanf("%d", &Size); int a[Size]; printf("Please Enter the Array Elements = "); for(i = 0; i < Size; i++) { scanf("%d", &a[i]); } printf("\nNumber of Times to Left Rotate an Array = "); scanf("%d", &num); for(i = 0; i < num; i++) { temp = a[0]; for(j = 0; j < Size - 1; j++) { a[j] = a[j + 1]; } a[Size - 1] = temp; } printf("\nArray Elements After Left Rotating Array : "); PrintArray(a, Size); return 0; }
C Program to Left Rotate Array Items using a while loop
#include<stdio.h> void PrintArray(int a[], int Size) { int i = 0; while(i < Size) { printf("%d \t ", a[i]); i++; } } int main() { int Size, i, j, num, temp; printf("\n Please Enter the Size = "); scanf("%d", &Size); int a[Size]; printf("\n Please Enter the Elements = "); i = 0; while(i < Size) { scanf("%d", &a[i]); i++; } printf("\n Number of Times to Left Rotate an Array = "); scanf("%d", &num); i = 0; while(i < num) { temp = a[0]; j = 0; while(j < Size - 1) { a[j] = a[j + 1]; j++; } a[Size - 1] = temp; i++; } printf("\n Elements After Left Rotating Array : "); PrintArray(a, Size); return 0; }
Please Enter the Size = 8
Please Enter the Elements = 22 33 44 55 66 77 88 99
Number of Times to Left Rotate an Array = 6
Elements After Left Rotating Array : 88 99 22 33 44 55 66 77
This C program rotates array items to the left hand side for the user given times 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 leftRotateArray(int a[], int size, int num) { for(int i = 0; i < num; i++) { int temp = a[0]; for(int j = 0; j < size - 1; j++) { a[j] = a[j + 1]; } a[size - 1] = temp; } } int main() { int size, num; printf("\nPlease Enter the Size = "); scanf("%d", &size); int a[size]; printf("\nPlease Enter the Elements = "); for(int i = 0; i < size; i++) { scanf("%d", &a[i]); } printf("\nNumber of Times to Left Rotate an Array = "); scanf("%d", &num); leftRotateArray(a, size, num); printf("\nElements After Left Rotating Array = "); PrintArray(a, size); }
Please Enter the Size = 10
Please Enter the Elements = 10 20 30 40 50 60 70 80 90 100
Number of Times to Left Rotate an Array = 4
Elements After Left Rotating Array = 50 60 70 80 90 100 10 20 30 40