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

Data Structure / Array

148

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:

#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;
}

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.


This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.