Write a program that deletes the first occurrence of an element in an array
Example
- A={0, 1, 0, 1, 2, 3, 1}
- Delete the first occurrence of 0
- A={1, 0, 1, 2, 3, 1}
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#define SIZE 100
void main()
{
int T[SIZE];
int i,j,n,nb;
do{
printf("Give the dimension: ");
scanf("%d", &n);
}while(n<=0||n>SIZE);
for(i=0;i<n;i++)
{
printf("Enter T[%d]=",i);
scanf("%d", &T[i]);
}
printf("Enter the value to be deleted: ");
scanf("%d", &nb);
for(i=0,j=0;i<n;i++)
{
if (T[i]==nb)
break;
}
if(i<n)// exit from the break
{
while(i<n-1)
{
T[i]=T[i+1];
i++;
}
n--;
}
for(i=0;i<n-1;i++)
printf("\t%d\n", T[i]);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Maximum width and depth