C Programming language

adplus-dvertising
C - Delete value from an Array
Previous Home Next

A program to delete an element from an array

To delete an element from a specified position we just have to shift the position of every element upward that are coming after the specified position, and when the element is deleted the array is resized to its now size i.e. one less than its actual size, here is a code snippet that shows how to delete an element from an array.

#include <stdio.h>
#include<conio.h>
int i, len,num, num_pos;
void main()
{
int arr[50];
clrscr();
del_element(arr, len, num, num_pos);
getch();
}
void del_element(int a[], len, num_pos)
{
printf("Enter the length of the array :");
scanf("\n%d", &len);
printf("\nEnter the array elements :");
scanf("\n%d",&a[i]);
printf("\nEnter the position of the number you want to delete :");
scanf("%d", &num_pos);
--num_pos;
if(num_pos>len)
{
    printf("deletion outside the array");
}
else
{
     for(i=num_pos; i<len; i++)
{
     a[i+1]=a[i];                    /* shifting all elements upwards */
}
num=a[num_pos];
len=len-1;                           /* resizing the newly formed array */
printf("\n After deletion now the array is :");
for(i=0; i<len; i++)
{
     printf("%d", a[i]);
}
}
}

Output : The output of the above program might be like this

Enter the length of the array : 4

Enter the array elements :

1

2

3

4

Enter the position of the number you want to delete : 3

After deletion now the array is :

1

2

4

Previous Home Next