C Program to delete an element from an array

This post explains the deletion of an element from an array using the C programming language.

C Program to delete an element from an array

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
    int arr[MAX_SIZE];
    int i, size, pos;

    //Input size and element in array
    printf("Enter size of the array : ");
    scanf("%d", &size);
    printf("\n Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    //Input element position to delete
    printf("\n Enter the element position to delete : ");
    scanf("%d", &pos);


    //Invalid delete position
    if(pos < 0 || pos > size)
    {
        printf("Invalid position!enter position between 1 to %d", size);
    }
    else
    {
        for(i=pos-1; i<size-1; i++)
        {
            arr[i] = arr[i + 1];
        }
            size--;

        //Print array after deletion
        printf("\nElements of array after delete are : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }
    }
    return 0;
}

Output

Explanation

This program helps to understand the deletion of an element from an array. We initialize variables where we can store values assigned by the users. Here MAX_SIZEisizepos are the variables to stored the values.

 We now get the size of the array from the user and store it in the variable named size. Then the user enters the elements in an array and also enters the position of an array to be deleted, the value of the position is stored in the variable pos

	int arr[MAX_SIZE];
    int i, size, pos;

    //Input size and element in array
    printf("Enter size of the array : ");
    scanf("%d", &size);
    printf("\n Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    //Input element position to delete
    printf("\n Enter the element position to delete : ");
    scanf("%d", &pos);

Now check the position of the variables with the use of the IF condition, whether the position satisfies the condition, if yes then allow the user to enter a position in an integer type, if no then use the for loop condition to proceed further.

	//Invalid delete position
    if(pos < 0 || pos > size)
    {
        printf("Invalid position!enter position between 1 to %d", 					size);
    }
    else
    {
        for(i=pos-1; i<size-1; i++)
        {
            arr[i] = arr[i + 1];
        }
            size--;

Subsequently we now proceed for displaying the elements deleted in an array.

		//Print array after deletion
        printf("\nElements of array after delete are : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }

We now get the fancied output.

%d