Design Develop and Implement Program in C for Inserting and Deleting an Element at a given valid Position.

Array representation by insertion of element at given position and deletion of element at given position and display it

3rd Sem Data structure and application lab 2nd Question.

Design, Develop and Implement a menu driven Program in C for the following Array operations
a. Inserting an Element (ELEM) at a given valid Position (POS)
b. Deleting an Element at a given valid Position (POS)
c. Display of Array Elements
d. Exit.
Support the program with functions for each of the above operations.

/*Design, Develop and Implement a menu driven Program in C for the following Array operations
a. Inserting an Element (ELEM) at a given valid Position (POS)
b. Deleting an Element at a given valid Position POS)
c. Display of Array Elements
d. Exit.
Support the program with functions for each of the above operations.*/

#include <stdio.h>
#include <stdlib.h>

#define MAX_ELEMENTS 100

void insertElement(int array[], int *n, int elem, int pos);
void deleteElement(int array[], int *n, int pos);
void displayArray(int array[], int n);

int main()
{
    int array[MAX_ELEMENTS];
    int choice, n, elem, pos;

    while (1)
    {
        printf("\nArray Operations:\n");
        printf("1. Insert an Element\n");
        printf("2. Delete an Element\n");
        printf("3. Display Array Elements\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1:
                printf("Enter the element to be inserted: ");
                scanf("%d", &elem);
                printf("Enter the position: ");
                scanf("%d", &pos);
                insertElement(array, &n, elem, pos);
                break;
            case 2:
                printf("Enter the position: ");
                scanf("%d", &pos);
                deleteElement(array, &n, pos);
                break;
            case 3:
                displayArray(array, n);
                break;
            case 4:
                exit(0);
            default:
                printf("Invalid choice\n");
        }
    }
    return 0;
}

void insertElement(int array[], int *n, int elem, int pos)
{
    int i;
    for (i = (*n) - 1; i >= pos; i--)
    {
        array[i + 1] = array[i];
    }
    array[pos] = elem;
    (*n)++;
}

void deleteElement(int array[], int *n, int pos)
{
    int i;
    for (i = pos; i < (*n) - 1; i++)
    {
        array[i] = array[i + 1];
    }
    (*n)--;
}

void displayArray(int array[], int n)
{
    int i;
    printf("Array elements:\n");
    for (i = 0; i < n; i++)
    {
        printf("%d\n", array[i]);
    }
}

Leave a Reply

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