AD1

Saturday, 17 June 2017

C program to left rotate an array

Write a program to left rotate an array by n position
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
Solution
#include <stdio.h>
#include <stdlib.h>
#define size 5
void rotate_array_left(int *array,int times)
{
int temp=0;
for(int x=0;x<times;x++)
{
temp=array[0];
for(int i=0;i<=size-2;i++)
{
array[i]=array[i+1];
}
array[size-1]=temp;
}
}
int main(int argc, char** argv) {
int data[size]={1,2,3,4,5};
rotate_array_left(data,2);
for(int j=0;j<=size-1;j++)
{
printf("%d\t",data[j]);
}
return (EXIT_SUCCESS);
}
view raw rotatearray.c hosted with ❤ by GitHub

No comments:

Post a Comment