Home / Programs / Insertion of an element at a specific index, write a c program
🚀 Programming Example

Insertion of an element at a specific index, write a c program

👁 206 Views
💻 Practical Program
📘 Step Learning

Insertion of an element at a specific index, write a c program

📌 Information & Algorithm

Given Input:

Enter the size of the array: 4
Enter the elements of the array: 1 2 3 4 5
Enter the index at which to insert element: 3
Enter the element to be inserted: 998
 

Expected Output:

Array after insertion: 1 2 3 998 4 

💻 Program Code

#include <stdio.h>

int main() {
    
    int n; // size of array
    int arr[100]; // array
    int index; // index at which to insert element
    
    printf("Enter the size of the array: ");
    scanf("%d", &n);

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

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

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

    for (int i = n; i > index; i--) {
        arr[i] = arr[i-1];
    }
    arr[index] = element;

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

    return 0;
}

                        

🖥 Program Output

Enter the size of the array: 4
Enter the elements of the array: 1 2 3 4 5
Enter the index at which to insert element: 3
Enter the element to be inserted: 998
Array after insertion: 1 2 3 998 4 
                            

📘 Explanation

This program takes the size of the array as input and creates an array of that size. The user is prompted to enter the elements of the array and the index at which they want to insert a new element. The user is also prompted to enter the element they want to insert. The program then shifts all elements after the specified index one position to the right and inserts the new element at the specified index. Finally, the program prints the modified array.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.