C Program to Insert an Element in Array

1. Introduction

Inserting an element in an array at a specified position is a fundamental operation in array manipulations. In this post, we'll guide you through the process of writing a C program to insert an element into an array at a given index and will explain each step in detail.

2. Program Overview

Our C program will:

1. Take the size of the array and its elements from the user.

2. Ask the user for the element they want to insert and its position.

3. Insert the given element at the specified position.

4. Display the new array to the user.

3. Code Program

#include <stdio.h>

int main() {
    int n, i, pos, value;
    int arr[100];
    
    // Take input for number of elements in the array
    printf("Enter the number of elements in array: ");
    scanf("%d", &n);
    
    // Take input for the elements
    printf("Enter %d integers:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Get value to insert and its position
    printf("Enter the value to insert: ");
    scanf("%d", &value);
    printf("Enter the position (0 to %d): ", n-1);
    scanf("%d", &pos);
    
    // Shifting elements to make space for new element
    for(i = n; i >= pos; i--) {
        arr[i+1] = arr[i];
    }
    
    // Inserting the new element
    arr[pos] = value;

    // Displaying the result
    printf("Resultant array is:\n");
    for(i = 0; i <= n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output:

Enter the number of elements in array: 5
Enter 5 integers:
12
25
24
10
2
Enter the value to insert: 56
Enter the position (0 to 4): 2
Resultant array is:
12 25 56 24 10 2

4. Step By Step Explanation

1. Variable Declaration:

- n stores the number of elements in the array.

- arr[100] is the array that will store our numbers.

- value will store the element we wish to insert.

- pos is the position at which the new element will be inserted.

2. Taking Input:

- First, we collect the number of elements from the user and then input each element.

- Then, we take the new value to be inserted and its desired position.

3. Inserting the Element:

- To insert the new element, we need to make space for it. We achieve this by shifting all elements from the desired position to the end, one place to the right.

- After creating the space, we can safely insert our new element.

4. Displaying the Modified Array: The new array, with the inserted value, is displayed.

Using this method, we can insert an element at any position in the array. However, note that this method assumes we're not exceeding the array's size (100 in this case). In real-world applications, you'd want to ensure that the array size is dynamic or at least check to avoid going beyond the array's size.

Comments