This blog is under construction

Saturday 29 June 2013

C program to insert an element in an unsorted array at given position

Write a C program to insert an element in an array at the desired position.


  #include <stdio.h>
  int main() {
        int data[100], i, n, pos, ele, flag = 0;

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

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

        while (1) {
                /* get the position and element from user */
                printf("Enter the pos & element to insert:\n");
                scanf("%d%d", &pos, &ele);

                /* inserting the new element */
                if (pos < 0 || pos > n + 1) {
                        printf("Wrong input for position!!\n");
                } else {
                        for (i = n; i >= pos; i--)
                                data[i] = data[i - 1];
                        data[pos - 1] = ele;
                        n++;
                }

                /* display the results */
                printf("After insertion operation:\n");
                for (i = 0; i < n; i++)
                        printf("%d ", data[i]);
                printf("\nDo you want to continue(0/1):");
                scanf("%d", &flag);
                if (!flag)
                        break;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:5
  Enter your inputs:
  100 200 300 400 500
  Enter the pos & element to insert:
  3   250
  After insertion operation:
  100 200 250 300 400 500 
  Do you want to continue(0/1):0



No comments:

Post a Comment