OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in C

Code snippet on how to insert an element at a specific index in an array in C

#include <stdio.h>

int main(){
  int i, index, n, value;
  int arr[20]; 

  printf("Enter the length of array: ");
  scanf("%d", &n);
  printf("Enter elements of array: \n");
  for(i = 0; i < n; i++){
    scanf("%d", &arr[i]);
  }

  printf("Enter the index at which element is to be inserted: ");
  scanf("%d", &index);

  printf("Enter value to insert: ");
  scanf("%d", &value);

  for(i = n; i > index; i--){
    arr[i] = arr[i-1];
  }
  arr[index] = value;
  printf("Array after insertion:\n");
  for(i = 0; i <= n; i++){
    printf("%d\n", arr[i]);
  }
  return 0;
}

This code allows a user to insert a value at a specific index in an array in C. The code starts by first setting up include stdio.h, then declaring variables (int i, index, n, value; int arr[20]). Then it asks the user to input the length of the array and it’s elements, and also the index and the value to insert. After that, the code moves the elements of the array that are after the index to one index ahead. Finally, it inserts the value at the indicated index and prints the output array.

c