C program to delete an 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.

Input elements:
Input position to delete: 2
Output: 10, 30, 40, 50

Required knowledge

Basic C programming, For loop, Array

Before you move on to this program you must have basic knowledge about arrays. How to read and print array elements using for loop.

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 an element from 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.


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

#include <stdio.h>

int main()
    int arr[100];
    int i, n, position;

     * Reads size and elements in array from user
    printf("Enter size of the array : ");
    scanf("%d", &n);

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

    // Reads the position to be deleted from user
    printf("Enter the element position to delete : ");
    scanf("%d", &position);

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

        // Decrement the size by 1

    // Prints the array after delete operation
    printf("\nElements of array after delete are : ");
    for(i=0; i<n; i++)
        printf("%d\t", arr[i]);

    return 0;

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 ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment