C Program to Count the Occurrences of Elements in a Linked List using Recursion

This C Program uses recursive function & finds the occurrence for an element in an unsorted list. The user enters the element need to be counted.

Here is the source code of the C program to find the number of occurrences of a given number in a list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to find the number of occurences of a given number in a 
  3.  * list
  4.  */
  5. #include <stdio.h>
  6.  
  7. void occur(int [], int, int, int, int *);
  8.  
  9. int main()
  10. {
  11.     int size, key, count = 0;
  12.     int list[20];
  13.     int i;
  14.  
  15.     printf("Enter the size of the list: ");
  16.     scanf("%d", &size);
  17.     printf("Printing the list:\n");
  18.     for (i = 0; i < size; i++)
  19.     {
  20.         list[i] = rand() % size;
  21.         printf("%d    ", list[i]);
  22.     }
  23.     printf("\nEnter the key to find it's occurence: ");
  24.     scanf("%d", &key);
  25.     occur(list, size, 0, key, &count);
  26.     printf("%d occurs for %d times.\n", key, count);
  27.     return 0;
  28. }
  29.  
  30. void occur(int list[], int size, int index, int key, int *count)
  31. {
  32.     if (size == index)
  33.     {
  34.         return;
  35.     }
  36.     if (list[index] == key)
  37.     {
  38.         *count += 1;
  39.     }
  40.     occur(list, size, index + 1, key, count);
  41. }

$ cc pgm13.c
$ a.out
Enter the size of the list: 7
Printing the list:
1    4    2    5    1    3    3
Enter the key to find it's occurence: 3
3 occurs for 2 times.

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Linked List, go to Linked List. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.