Software & Finance Forums

### Author Topic: Turbo C Program to rotate elements in array (left and right direction)  (Read 5155 times)

#### kathir

• Sr. Member
• Posts: 283
##### Turbo C Program to rotate elements in array (left and right direction)
« on: January 11, 2012, 03:02:28 pm »
Here is Turbo C Program to rotate elements in array (left and right direction).

Code:
```//Source Code Listing

#include <stdio.h>

void RotateLeft(int *arr, int max, int numTimes)
{
int i, j, temp;
for(j = 0; j < numTimes; j++)
{
temp = arr[0];
for(i = 0; i < max; i++)
arr[i] = arr[i + 1];
arr[max - 1] = temp;
}
}

void RotateRight(int *arr, int max, int numTimes)
{
int i, j, temp;
for(j = 0; j < numTimes; j++)
{
//rotate right once
temp = arr[max - 1];
for(i = max - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = temp;
}
}

void PrintArray(int *arr, int max)
{
int i;
for(i = 0; i < max; i++)
{
printf("%3d", arr[i]);
if(i < max - 1)
printf(", ");
else
printf("\n");
}
}

void main()
{
#define MAX_NUMBERS 10
int arr[MAX_NUMBERS];
int i, j, k;

for(i = 0; i < MAX_NUMBERS; i++)
arr[i] = (i + 1) * 10;

// Number of times to shift
k = 4;

PrintArray(arr, MAX_NUMBERS);

printf("Rotating Left now\n");
for(j = 0; j < k; j++)
{
RotateLeft(arr, MAX_NUMBERS, 1);
PrintArray(arr, MAX_NUMBERS);
}

printf("Rotating Right now\n");
for(j = 0; j < k; j++)
{
RotateRight(arr, MAX_NUMBERS, 1);
PrintArray(arr, MAX_NUMBERS);
}
}

/***
10,  20,  30,  40,  50,  60,  70,  80,  90, 100
Rotating Left now
20,  30,  40,  50,  60,  70,  80,  90, 100,  10
30,  40,  50,  60,  70,  80,  90, 100,  10,  20
40,  50,  60,  70,  80,  90, 100,  10,  20,  30
50,  60,  70,  80,  90, 100,  10,  20,  30,  40
Rotating Right now
40,  50,  60,  70,  80,  90, 100,  10,  20,  30
30,  40,  50,  60,  70,  80,  90, 100,  10,  20
20,  30,  40,  50,  60,  70,  80,  90, 100,  10
10,  20,  30,  40,  50,  60,  70,  80,  90, 100
Press any key to continue . . .
***/

```

Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.