Write an interactive C program to insert new elements in the unsorted array.

, , No Comments

 Certainly! Below is an interactive C program that allows the user to insert new elements into an unsorted array:


```c

#include <stdio.h>


void displayArray(int arr[], int size) {

    printf("Array elements: ");

    for (int i = 0; i < size; i++) {

        printf("%d ", arr[i]);

    }

    printf("\n");

}


void insertElement(int arr[], int *size, int element, int position) {

    // Check if the array is full

    if (*size >= 100) {

        printf("Array is full. Cannot insert more elements.\n");

        return;

    }


    // Shift elements to make space for the new element

    for (int i = *size; i > position; i--) {

        arr[i] = arr[i - 1];

    }


    // Insert the new element at the specified position

    arr[position] = element;


    // Increment the size of the array

    (*size)++;

}


int main() {

    int arr[100];

    int size = 0;

    int element, position;


    // Input the initial array

    printf("Enter the number of elements in the array: ");

    scanf("%d", &size);


    printf("Enter %d elements:\n", size);

    for (int i = 0; i < size; i++) {

        scanf("%d", &arr[i]);

    }


    // Display the initial array

    displayArray(arr, size);


    // Input the element to be inserted

    printf("Enter the element to be inserted: ");

    scanf("%d", &element);


    // Input the position where the element should be inserted

    printf("Enter the position to insert the element (0 to %d): ", size);

    scanf("%d", &position);


    // Validate the position

    if (position < 0 || position > size) {

        printf("Invalid position. Element cannot be inserted.\n");

    } else {

        // Insert the element

        insertElement(arr, &size, element, position);


        // Display the updated array

        displayArray(arr, size);

    }


    return 0;

}

```


This program allows the user to input the initial array, the element to be inserted, and the position at which the element should be inserted. The `insertElement` function is responsible for shifting the elements and inserting the new element at the specified position. The `displayArray` function is used to display the array before and after the insertion.

0 टिप्पणियाँ:

Post a Comment