C program to delete element from an array

Write a C program to delete an element from an array at specified position. How to remove an element from array at given position. Logic to remove an element from any given position in an array. The program should also print an error message if the delete position is invalid.

Example

Input

Input array elements: 10 20 30 40 50
Input position to delete: 2

Output

Array elements: 10, 30, 40, 50

Required knowledge

Basic C programming, For loop, Array

Must know - Program to read and print array elements

Logic to remove an element from array

Array is a linear data structure. It provides an index based fast mechanism to access its elements. But insertion or deletion from an array is time taking process.
Literally speaking there isn't anything such as deleting an element from an array. In general you copy elements of the array towards left. Suppose I say you need to delete the 2nd element from the given array. You will do it as.

Delete element from an array in C

Below is the step by step descriptive logic to remove any element from an array.

  1. Move to the specified location which you want to remove in the given array.
  2. Copy the next element to the current element of the array. Which is you need to perform array[i] = array[i + 1].
  3. Repeat the above steps till last element of the array.
  4. Finally decrement the size of array by one.

Program to delete element from array

/*
 * C program to delete an element from array at specified position
 */

#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("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

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

    /* If delete position is invalid */
    if(pos==size+1 || pos<0)
    {
        printf("Invalid position! Please enter position between 1 to %d", size);
    }
    else
    {
        /* Copy next element value to current element */
        for(i=pos-1; i<size-1; i++)
        {
            arr[i] = arr[i + 1];
        }

        /* Decrement array size by 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

Enter size of the array : 5
Enter elements in array : 10 20 30 40 50
Enter the element position to delete : 2

Elements of array after delete are : 10      30      40      50

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>