C Program Count the Number of Occurrences of an Element an array using Recursion - Source code
/*
C program to find the number of occurrences of a given number in a
list */
#include <stdio.h>
void occur(int [], int, int, int, int *);
int main()
{
int size, key, count = 0;
int list[40];
int i;
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Printing the list:\n");
for (i = 0; i < size; i++)
{
list[i] = rand() % size;
printf("%d ", list[i]);
}
printf("\nEnter the key to find it's occurrence: ");
scanf("%d", &key);
occur(list, size, 0, key, &count);
printf("%d occurs for %d times.\n", key, count);
return 0;
}
void occur(int list[], int size, int index, int key, int *count)
{
if (size == index)
{
return;
}
if (list[index] == key)
{
*count += 1;
}
occur(list, size, index + 1, key, count);
}
Program Explanation
1. First, an array is created with random elements using the rand() function.
2. To find the occurrences of an element in the list, element at the index 0 in the list is compared with the key and, if matched, the count is incremented by one.
3. The step 2 is repeated for each element in the list by increasing the value of index by 1 each time.