This blog is under construction

Saturday 27 July 2013

C program to split an array at the given position and move the second part to the front

Write a C program to split an array at the given position and move the second part to the start.


  #include <stdio.h>
  #define MAX 256

  /* prints the contents of the given array */
  void printArray(int *data, int n) {
        int i;

        printf("Resultant Array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", *(data + i));
        }
        printf("\n");
        return;
  }

  int main() {
        int input[MAX], output[MAX];
        int i, j = 0, n, pos;

        /* get the number of array entries from the user */
        printf("Enter the number of array entries:");
        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", &input[i]);
        }

        /* get the position to split  the input array */
        printf("Position to split the given array(1-%d):", n);
        scanf("%d", &pos);

        /* boundary check */
        if (pos < 1 || pos > n) {
                printf("Wrong position!!\n");
                return 0;
        }

        /* incase the position is at the end of the array */
        if (pos == n) {
                printArray(input, n);
                return 0;
        }

        /* copying second part to front */
        for (i = pos; i < n; i++) {
                output[j++] = input[i];
        }

        /* copyint the front part to last */
        for (i = 0; i < pos; i++) {
                output[j++] = input[i];
        }

        /* print the result */
        printArray(output, j);
        return 0;

  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array entries:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40
  Data[4]: 50
  Position to split the given array(1-5):3

  Resultant Array:
  40  50  10  20  30 


No comments:

Post a Comment