This blog is under construction

Thursday 25 July 2013

C program to insert an element into an array

Write a C program to insert an element in an array.


  #include <stdio.h>
  #define MAX 256

  int main() {
        int i, n, ele, pos, temp, arr[MAX];

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

        /* boundary check */
        if (n < 0 || n > MAX) {
                printf("Boundary Exceeded!!\n");
                return 0;
        }

        /* 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", &arr[i]);
        }

        /* get the new element and its position to insert */
        printf("Enter the element and position to insert:");
        scanf("%d%d", &ele, &pos);

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

        /* shift the element to insert the new one */
        for (i = n; i >= pos; i--) {
                arr[i] = arr[i - 1];
        }
        /* insert the new element */
        arr[pos - 1] = ele;

        /* print the results */
        printf("Elements in the resultant array:\n");
        for (i = 0; i <= n; i++) {
                printf("%d ", arr[i]);
        }

        printf("\n");

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of array elements:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 40
  Data[4]: 50
  Enter the element and position to insert:60 6
  Elements in the resultant array:
  10 20 30 40 50 60 


No comments:

Post a Comment