C Program Count the Number of Occurrences of an Element an array using Recursion
C Program Count the Number of Occurrences of an Element an array using Recursion
Problem Description
This C Program uses recursive function & finds the occurrence for an element in an unsorted list. The user enters the number of elements in the list and the key whose count in the list is to find.
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 Output
Enter the size of the list: 25 Printing the list: 16 17 9 0 19 24 3 8 12 14 5 20 6 2 11 16 20 17 2 11 16 4 2 3 17 Enter the key to find it's occurrence: 17 17 occurs for 3 times.
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.