How to Delete Element from an Array.

This post covers the procedure, algorithm, and code on how to delete elements from an array.

To perform the deletion of elements from an array in C, you typically need to shift the remaining elements to fill the gap left by the deleted element.

Algorithm

INPUT: An array A[l…u] and KEY IS THE ELEMENT TO BE DELETED
OUTPUT: Array A without KEY or unsuccessful message
DATA STRUCTURE: Single-Dimensional Array

STEP 1: I=SEARCHARRAY(KEY)
STEP 2: IF(I==-1)THEN
STEP 3: PRINT("ELEMENT NOT PRESENT , DELETION NOT POSSIBLE")
STEP 4: EXIT
STEP 5: ELSE
STEP 6: WHILE(I<U)DO
STEP 7: A[I]=A[I+1]
STEP 8: I=I+1
STEP 9: ENDWHILE
STEP 10: U=U-1
STEP 11: ENDIF
STEP 12 STOP

Code

#include <stdio.h>
int deletion();
int a[]={1,5,3,2,1};
int linearsearch(int);
int key;
int main()
{
int pos=0;
printf("ENTER THE ELEMENT TO BE DELETED");
scanf("%d",&key);
deletion();
for(int j=0;j<5;j++)
{
printf("%d ",a[j]);
}
return 0;
}
int linearsearch(int n){
int i,flag=0,pos=-1;
while(i<5&&flag==0) 
{
if(n==a[i])
{
flag=1;
pos=i;
break;
}
else
i++;
}
return pos;
}
int deletion()
{ int u=5;
int i=linearsearch(key);
if(i==-1)
{
printf("element not present: deletion not possible");
}
else
{
while(i<u)
{
a[i]=a[i+1];
i++;
}
u=u-1;
}
return 0;
}

The above code is used in deleting elements from an array and then shifting the remaining elements to fill in the gap.

Output

$: ENTER THE ELEMENT TO BE DELETED 5
1 3 2 1 0

Click here to get the algorithm and code for a 2D array performing Matrix multiplication.

Click here to get the algorithm and code for merging together two arrays.

Leave a Comment

Your email address will not be published. Required fields are marked *