OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in C

Code snippet on how to insert an element at the beginning of an array in C

#include <stdio.h>
#define MAXSIZE 32

int arr[MAXSIZE];
int n = 0; // number of elements in the array

void insert_at_start(int element) {
  int i;
  // move all elements one step right
  for(i = n - 1; i >= 0; i--)
    arr[i+1] = arr[i];

  arr[0] = element; // insert element at start
  n++; // increment the size
}

This code inserts an element at the beginning of an array. It begins by including the standard input/output library and defining a maximum size for the array. It then declares a global array and a counter for the number of elements.

The function then takes a parameter of the element to be inserted. It starts a loop that moves all elements one step to the right and replaces the previous element at each step. After the loop is finished, the element is inserted at the start and the element count is incremented.

c