Insert the element after the given index of array
#include <conio.h>
#define MAX 5
void main()
{
int array[MAX] = {1, 2, 4, 5};
int N = 4; // Used for number of elements in array
int i = 0; // Used for loop variable
int index = 1; // Used for indexing location after which value will be inserted
int value = 3; // new data element to be inserted
// Used for printing array before insertion
printf("Printing array before insertion −\n");
for(i = 0; i < N; i++)
{
printf("array[%d] = %d \n", i, array[i]);
}
// now shift rest of the elements downwards using it
for(i = N; i >= index + 1; i--)
{
array[i + 1] = array[i];
}
// add new element at first position
array[index + 1] = value;
// 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]);
}
}
When we compile and run the this 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