Find number of occurrences of an element in an array
C program to find number of occurrences of an element in one dimensional 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]);
}
}
int occ_ele(int a[MAX], int n, int num)
{
int i, count;
count = 0;
for(i=0;i<n;i++)
{
if(a[i] == num)
count++;
}
return(count);
}
void main()
{
int arr[MAX];
int i, n, count, 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 whose number of occurrences is to be found\t:");
scanf("%d",&num);
count = occ_ele(arr, n, num);
printf("\n%d occur %d number of times in the array",num,count);
getch();
}
Output
Enter the number of elements in the array :5
Enter the elements of the array
Element 1 :1
Element 2 :2
Element 3 :1
Element 4 :2
Element 5 :3
Enter the element whose number of occurrences is to be found :1
1 occur 2 number of times in the array