C Program to Insert an Element at the Beginning of an Array

In this article, we will write a C program to insert an element at the beginning of an array. We are basically given an array of size N and our task is to take a number from the user as input and insert it at the beginning of the array.

Sample Example:

Input: 
Enter the size of the array: 5
Enter the Elements of the array: 2 3 4 5 6
Enter the element to be inserted: 20

Output:
Array after inserting element: 20 2 3 4 5 6

In the C programming language, an array is a collection of items that are stored in contiguous memory locations.

This means that if we want to insert an element at the beginning of an array, we have to first shift all the existing elements of the array to the right side by one index and then we can put the given element at the 0th index of the array.

Finally, we have to increase the size of the array by one so that the last element is not skipped while printing.

The following C program shows how you can insert an element at the beginning of an array:

// C Program to insert an element at the beginning of an array

#include <stdio.h>
#include <conio.h>

int main() {

    int arr[100], size, elem;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    printf("Enter the Elements of the array: ");
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Enter the element to be inserted: ");
    scanf("%d", &elem);

    // Shift array elements the right side by one place
    for (int i = size; i > 0; i--) {
        arr[i] = arr[i - 1];
    }

    // Insert element at the beginning
    arr[0] = elem;
    size = size + 1; // Increment size by 1

    printf("Array after inserting element: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;

}

Output:

Enter the size of the array: 5
Enter the Elements of the array: 20 30 40 50 60
Enter the element to be inserted: 10
Array after inserting element: 10 20 30 40 50 60

Time Complexity: O(N), Where N is the number of elements in the array.

Note: When inserting an element at the beginning of an array and shifting existing elements to the right, you need to ensure that there is enough space for the new element and that the array has one extra slot.

I hope you will find this article helpful. Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment