Programs


Title : WAP to find the number of times occurs a given number in an array

#include <stdio.h>

int BinSearch(int arr1[], int n, int x, int searchFirst)

{

   int low = 0, high = n - 1;

   int result = -1;

   while (low <= high)

   {

       int mid = (low + high) / 2;

       if (x == arr1[mid])

       {

           result = mid;

           if (searchFirst)

               high = mid - 1;

           else

               low = mid + 1;

       }

       else if (x < arr1[mid])

           high = mid - 1;

       else

           low = mid + 1;

   }

   return result;

}

int main(void)

{

   int arr1[] = {2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6};

   int srch_num = 6;

   int n = sizeof(arr1) / sizeof(arr1[0]);

   int i;

     printf("The given array is :  ");

   for (i = 0; i < n; i++)

   {

       printf("%d  ", arr1[i]);

   }

   printf("\n");

     int first = BinSearch(arr1, n, srch_num, 1);

   int last = BinSearch(arr1, n, srch_num, 0);

   int ctr = last - first + 1;

   if (first != -1)

       printf("The number of times the number %d occurs in the given array is:  %d", srch_num, ctr);

   else

       printf("No such element found in the array.");

   return 0;

}

OUTPUT:

The given array is :  2  2  3  3  4  4  4  5  5  6  6  6 

The number of times the number 6 occurs in the given array is:  3

Related Topics

  • Integer x appears more than n by 2 times in sorted array

      Jan 15, 2022

  • Program to find majority element of an array

      Jan 03, 2022

  • Program to print a matrix in spiral form

      Jan 03, 2022

  • WAP to find the maximum circular sub array sum of given array

      Jan 03, 2022

  • Program to count the number of triangles from a given array

      Jan 03, 2022

  • Program to sort an array of 0s, 1s and 2s.

      Jun 30, 2021

  • Subscribe Now