Page 83 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 83

Fundamentals of Data Structures




                    Notes              Deleting an element
                                       Merging arrays
                                   Let us now write a function that deletes an element from an array. The function in the listing
                                   given below takes the name of the array (which is actually a pointer to an int), the index of the
                                   element to be removed and the index of the last element as arguments.

                                       !

                                     Caution  A function which deletes an element removes the element and returns the index of
                                     the last element.
                                   A function to delete an element from an array is given below.
                                   int delete_element(int *list, int last_index, int index)
                                   {
                                   int i;
                                   for (i = index; i < last_index; i ++)
                                   list [i]=list [i+l];
                                   return (last_index-1);
                                   }
                                   Let us now see how to insert an element in an array. Array insertion does not mean increasing
                                   size of array.


                                          Example: consider an array a[10] having three elements in it initially and a[0] = 1, a[1] =
                                   2 and a[2] = 3 and you want to insert a number 45 at location 1 i.e. a[0] = 45, so we have to
                                   move elements one step below so after insertion a[1] = 1 which was a[0] initially, and a[2] = 2 and
                                   a[3] = 3.
                                   A program to insert an element in an array is given as below:
                                   #include <stdio.h>


                                   int main()
                                   {
                                   int array[100], position, c, n, value;


                                   printf("Enter number of elements in array\n");
                                   scanf("%d", &n);
                                   printf("Enter %d elements\n", n);
                                   for (c = 0; c < n; c++)
                                   scanf("%d", &array[c]);
                                   printf("Enter the location where you wish to insert an element\n");
                                   scanf("%d", &position);


                                   printf("Enter the value to insert\n");
                                   scanf("%d", &value);






          76                                LOVELY PROFESSIONAL UNIVERSITY
   78   79   80   81   82   83   84   85   86   87   88