c code for number appears more than or equal to n/2 times

  • c
  • write a c code for number appears more than or equal to n/2 times

    Given a sorted array of length n, WAP to find the number in an array that appears more than or equal to n/2 times. It can be assumed that such an element always exists. Input: 2 3 3 4 Output: 3 Input: 3 4 5 5 5 Output: 5

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> int ocurrence(int *A, int n, int o) { int count = 0; for (int i = 0; i < n; i++) { if (A[i] == o) { count++; } } return count; } int search_by_n2(int *A, int n) { int num; for (int i = 0; i < n; i++) { int counter = ocurrence(A, n, A[i]); int n2 = A[i] / 2; if (counter >= n2) { num = A[i]; } } return num; } int main() { int n; printf("enter the number of elemnts : "); scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("Element Found is : %d \n", search_by_n2(arr, n)); return 0; }