C Program to Find if a given Integer X appears more than N/2 times in a Sorted Array of N Integers

«
»
This C Program checks if a given integer X appears more than N/2 times in a sorted array of N integers.

Here is source code of the C Program to find if a given integer X appears more than N/2 times in a sorted array of N integers. 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 if a given Integer X appears more than N/2 times in a Sorted Array of N Integers
  3.  */
  4. # include <stdio.h>
  5. # define bool int
  6.  
  7. bool Morenooftimes(int array[], int n, int x)
  8. {
  9.     int i;
  10.     int final_index = n % 2 ? n / 2 : (n / 2 + 1);
  11.  
  12.     for (i = 0; i < final_index; i++)
  13.     {
  14.         /* check if x is presents more than n/2 times */
  15.         if (array[i] == x && array[i + n / 2] == x)
  16.             return 1;
  17.     }
  18.     return 0;
  19. }
  20.  
  21. int main()
  22. {
  23.     int array[] = {10, 15, 15, 12, 17 ,15};
  24.     int n = sizeof(array) / sizeof(array[0]);
  25.     int x = 15;
  26.     if (Morenooftimes(array, n, x))
  27.         printf("The given no %d appears more than %d times in array[]", x, n/2);
  28.     else
  29.         printf("The given no %d does not appear more than %d times in array[]", x, n/2);
  30.     getchar();
  31.     return 0;
  32. }

advertisement
$ cc pgm95.c
$ a.out
The given no 15 appears more than 3 times in array[]

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

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

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

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!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter