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
void occur(int , int, int, int, int *);
int size, key, count = 0;
printf("Enter the size of the list: ");
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: ");
occur(list, size, 0, key, &count);
printf("%d occurs for %d times.\n", key, count);
void occur(int list, int size, int index, int key, int *count)
if (size == index)
if (list[index] == key)
*count += 1;
occur(list, size, index + 1, key, count);
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.