Delete first occurrence of the number from the array
C program to delete first occurrence of the number from the array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void delete(int a[MAX], int n, int num)
{
int i, flag, pos;
flag = 0;
for(i=0;i<n;i++)
{
if(a[i] == num)
{
pos = i;
flag = 1;
break;
}
}
if(flag == 1)
{
for(i=pos;i<=n-1;i++)
{
a[i] = a[i+1];
}
printf("\nModified array is\n");
print_array(a, n-1);
}
else
{
printf("\nElement to be deleted not found");
}
}
void main()
{
int arr[MAX];
int i, n, num;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
printf("Enter the element to be deleted\t:");
scanf("%d",&num);
delete(arr, n, num);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :56
Element 5 :12
Element 6 :25
Element 7 :56
Element 8 :21
Enter the element to be deleted :56
Modified array is
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :12
Element 5 :25
Element 6 :56
Element 7 :21