C program to Insert and Delete an element from a 1-D static array

Source Code

#include <stdio.h>
#define MAX 5

// utility function to print array elements
void printArray(int arr[], int size)
{
    for (int i = 0; i <= size; i++)
        printf("%d, ", arr[i]);

    printf("\n");
}

int main()
{
    int arr[MAX], choise, num, size = -1;

    do
    {
        printf("1. Insert \t 2. Delete \t 3. Display \t 4. Exit \n");
        scanf("%d", &choise);

        switch (choise)
        {
        case 1:
            // insertion
            if (size == MAX - 1)
                printf("Array is full\n");
            else
            {
                printf("Enter the number to add: ");
                scanf("%d", &num);
                size++;
                arr[size] = num;
            }
            break;
        case 2:
            // deletion
            if (size == -1)
                printf("Array is empty\n");
            else
            {
                printf("Enter the number to delete: ");
                scanf("%d", &num);
                int i;
                for (i = 0; i <= size; i++)
                {
                    if (arr[i] == num)
                    {
                        for (int j = i; j <= size; j++)
                            arr[j] = arr[j + 1];
                        size--;
                        printf("%d is deleted!\n", num);
                        break;
                    }
                }
                if (i == size + 1)
                    printf("Element not found\n");
            }
            break;
        case 3:
            printArray(arr, size);
            break;
        case 4:
            printf("EXITING...\n");
            break;
        default:
            printf("Invalid choise! Please try again!\n");
            break;
        }
    } while (choise != 4);

    return 0;
}

Time Complexity

1. for Insertion Operation

  • O(1)

2. for Deletion Operation

  • O(n) where 'n' is the current size of the array

Other videos in this series

Back To Home