Write a C program to delete element from array at specified position. How to remove element from array at given position in C programming. Logic to remove element from any given position in array in C program. 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 Input Output, For loop, Array
Logic to remove element from array
Array is a linear data structure. It provides index based fast mechanism to access its elements. But insertion or deletion from an array is a costly operation.
Literally speaking there isn’t anything such as deleting element from array. In general you copy elements of the array towards left. Suppose I say you need to delete the 2nd element from given array. You will do it as.
Step by step descriptive logic to remove element from array.
- Move to the specified location which you want to remove in given array.
- Copy the next element to the current element of array. Which is you need to perform
array[i] = array[i + 1]
. - Repeat above steps till last element of array.
- 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);
/* Invalid delete position */
if(pos < 0 || pos > size)
{
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 😉