You are here

C program to insert an element in an array

C program to insert an element in an array, for 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. Array insertion does not mean increasing its size i.e array will not contain 11 elements.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.    int array[100], position, c, n, value;
  6.  
  7.    printf("Enter number of elements in array\n");
  8.    scanf("%d", &n);
  9.  
  10.    printf("Enter %d elements\n", n);
  11.  
  12.    for (c = 0; c < n; c++)
  13.       scanf("%d", &array[c]);
  14.  
  15.    printf("Enter the location where you wish to insert an element\n");
  16.    scanf("%d", &position);
  17.  
  18.    printf("Enter the value to insert\n");
  19.    scanf("%d", &value);
  20.  
  21.    for (c = n - 1; c >= position - 1; c--)
  22.       array[c+1] = array[c];
  23.  
  24.    array[position-1] = value;
  25.  
  26.    printf("Resultant array is\n");
  27.  
  28.    for (c = 0; c <= n; c++)
  29.       printf("%d\n", array[c]);
  30.  
  31.    return 0;
  32. }

Output of program:
 C program output to insert an element in an array

Download Insert element in array program.