Monday 26 September 2016

Insertion Operation on Array- on specific Index

C Program to Insert the element onto the specific location of the array.
#include <stdio.h>
#include <conio.h>
#define MAX 5
void main()
{
   int array[MAX] = {1, 2, 4, 5};
 
   int N = 4;        // Number of total elements in array
   int i = 0;        // Use as loop variable
   int index = 2;    // Use as index location to insert new value
   int value = 3;    // Use as new data element to be inserted
 
   printf("Printing array before insertion −\n");  // print array before insertion
    for(i = 0; i < N; i++) {
      printf("array[%d] = %d \n", i, array[i]);
   }
 
// now shift rest of the elements downwards  
    for(i = N; i >= index; i--)
 {
      array[i+1] = array[i];
   }
   // Now, add new element at first position
   array[index] = value;
   // used to increase N to reflect number of elements
   N++;
   // print to confirm
   printf("Printing array after insertion −\n");
   for(i = 0; i < N; i++) {
      printf("array[%d] = %d\n", i, array[i]);
   }
}

If we compile and run the above program, it will produce the following result −

Printing array before insertion −
array[0] = 1
array[1] = 2
array[2] = 4
array[3] = 5

Printing array after insertion −
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5


EmoticonEmoticon