Write a program that reads an array and rotates it to left by n positions.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
int A[SIZE];
int N;
int i, j, aux;
int position;
do {
printf("Enter N: ");
scanf("%d", &N);
} while (N <= 0 || N > SIZE);
printf("Enter A: ");
for (i = 0;i < N;i++)
scanf("%d", &A[i]);
do {
printf("Enter number of positions (< %d): ", N);
scanf("%d", &position);
} while (position <= 0 || position >= N);
// we will left shit position times
for(j=1; j <=position; j++)
{
// we save the first element
aux=A[0];
// we left forward each element one position
for(i=0; i<N-1; i++)
A[i]=A[i+1];
A[N-1]=aux;
}
printf("After left rotating by %d positions : ", position);
for(i=0; i<N; i++)
printf("%d ", A[i]);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using merge-sort algorithm