This blog is under construction

Saturday, 27 July 2013

C program to rotate an array left by n places

Write a C program to rotate an array left by n places.


  #include <stdio.h>
  #define MAX 256

  int main() {
        int i, j, n, tmp, shift, data[MAX];

        /* get the number of array entries from the user */
        printf("Enter the number of elements in input array:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &data[i]);
        }

        /* get the rotation input */
        printf("Rotate the array elements left by ");
        scanf("%d", &shift);

        /* rotate an array left by given(shift) places */
        for (i = 0; i < shift; i++) {
                tmp = data[0];
                for (j = 1; j <= n - 1; j++) {
                        data[j - 1] = data[j];
                }
                data[n - 1] = tmp;
        }

        /* print the resulatant array */
        printf("Resultant array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", data[i]);
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements in input array:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 50
  Data[4]: 40
  Rotate the array elements left by 3
  Resultant array:
  50  40  10  20  30 


2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete