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

This C Program, using iteration, 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 Count the Number of Occurrences of an Element in the Linked List 
  3.  * without using Recursion
  4.  */
  5. #include <stdio.h>
  6.  
  7. int occur(int [], int, int);
  8.  
  9. int main()
  10. {
  11.     int size, key, count;
  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.     count = occur(list, size, key);
  26.     printf("%d occurs for %d times.\n", key, count);
  27.     return 0;
  28. }
  29.  
  30. int occur(int list[], int size, int key)
  31. {
  32.     int i, count = 0;
  33.  
  34.     for (i = 0; i < size; i++)
  35.     {
  36.         if (list[i] == key)
  37.         {
  38.             count += 1;
  39.         }
  40.     }
  41.     return count;
  42. }

$ gcc occurnumber.c -o occurnumber
$ a.out
Enter the size of the list: 10
Printing the list:
3    6    7    5    3    5    6    2    9    1   
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.