C Program to delete an element from array

Category: C Program

C Program to delete an element from an array by given index or by given value. How to remove an element from an array? An element can be deleted by shifting all the next element back to one position.

C Program to delete an element from array at given position

#include <stdio.h>

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

    printf("Enter number of elements: ");
    scanf("%d", &size);

    printf("Enter array elements-\n");
    for (i = 0; i < size; i++)
        scanf("%d", &arr[i]);

    printf("\nEnter postion to delete: ");
    scanf("%d", &pos);

    for(i = pos-1; i < size-1; i++)
        arr[i] = arr[i + 1];
    size--;

    printf("Array after deletion-\n");
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

Output

Enter number of elements: 5

Enter array elements-
2
3
1
6
4

Enter postion to delete: 3

Array after deletion-
2 3 6 4

C Program to delete an element from array by given value

#include <stdio.h>

void main()
{
    int arr[50], size, pos, num, i;

    printf("Enter number of elements: ");
    scanf("%d", &size);

    printf("Enter array elements-\n");
    for (i = 0; i < size; i++)
        scanf("%d", &arr[i]);

    printf("\nEnter element to delete: ");
    scanf("%d", &num);

    // get the position of element to deleted
    for (i = 0; i < size; i++)
    {
        if (arr[i] == num)
        {
            pos = i + 1;
            break;
        }
    }

    for (i = pos-1; i < size-1; i++)
        arr[i] = arr[i + 1];
    size--;

    printf("Array after deletion-\n");
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

Output

Enter number of elements: 5

Enter array elements-
2
3
5
4
1

Enter element to delete: 5

Array after deletion-
2 3 4 1

Recommended Posts