C Program to Insert at nth Position in Array

programming

Problem: Write a C program to insert the given element at nth position in a array.

To solve this problem, we will assume the array is large enough to store all the elements.

#include <stdio.h>

// Function to insert an element at the nth position in an array
void insertElement(int array[], int n, int element, int position) {
    // Loop through the array starting from the end
    for (int i = n - 1; i >= position; i--) {
        // Shift all elements to the right of the position
        array[i + 1] = array[i];
    }
    // Insert the new element at the position
    array[position] = element;
}

int main() {
    // Declare an array
    int array[] = {1, 2, 3, 4, 5};
    int n = sizeof(array) / sizeof(array[0]); // calculate the number of elements in the array
    int element = 6; // element to be inserted
    int position = 3; // position where the element should be inserted

    // Print the original array
    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    // Insert the element at the specified position
    insertElement(array, n, element, position);

    // Print the updated array
    printf("Updated array: ");
    for (int i = 0; i < n + 1; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0;
}

Output:

Original array: 1 2 3 4 5 
Updated array: 1 6 2 3 4 5

This program defines a function called insertElement that takes in an array, the number of elements in the array, an element to be inserted, and the position at which the element should be inserted.

The function uses a loop to shift all elements to the right of the specified position one spot to the right, and then inserts the new element at the specified position.

The main function then declares an array and calls the insertElement function to insert an element at a specified position, printing the original and updated arrays for demonstration purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *