Write pseudo code to count occurrence of a given number in the list. For example, consider the following list, if user enters 5 then display “2 times” because “5” occurs 2 times in the list.
Given Array
int A[] = {5, 3, 6, 8, 5, 1};
Write pseudo code to count occurrence of a given number in the list. For example, consider the following list, if user enters 5 then display “2 times” because “5” occurs 2 times in the list.
Solution :
By using C Language.
#include <stdio.h>int BinarySearch(int A[], 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 == A[mid]){result = mid;if (searchFirst)high = mid - 1;elselow = mid + 1;}else if (x < A[mid])high = mid - 1;elselow = mid + 1;}return result;}int main(void){int A[] = {5, 3, 6, 8, 5, 1};int target = 5;int n = sizeof(A)/sizeof(A[0]);int first = BinarySearch(A, n, target, 1);int last = BinarySearch(A, n, target, 0);int count = last - first + 1;if (first != -1)printf("Element %d occurs %d times.", target, count);elseprintf("Element not found in the array.");return 0;}
Output : Element 5 occurs 2 times
Question :
Write pseudo code to count occurrence of a given number in the list. For example, consider the following list, if user enters 5 then display “2 times” because “5” occurs 2 times in the list.
Solution:
As above mentioned.
ATTENTION
Please let me know if you have any questions. I hope the above is useful to you.