In this program, we are going to share a C++ program to find the majority number. If you are c++ beginner OR want to start learning the C++ programming language, then keep your close attention in this tutorial as we are going to share a c++ program to find the majority number with the output.
Copy the below C++ program and execute it with the help of Turbo C compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <bits/stdc++.h> using namespace std; void findMajority(int arr[], int n) { int maxCount = 0; int index = -1; for(int i = 0; i < n; i++) { int count = 0; for(int j = 0; j < n; j++) { if(arr[i] == arr[j]) count++; } if(count > maxCount) { maxCount = count; index = i; } } if (maxCount > n/2){ cout << arr[index] << endl; } else { cout << "No Majority Element" << endl; } } int main() { int arr[] = {5, 4, 2, 5, 3, 5, 5}; int n = sizeof(arr) / sizeof(arr[0]); findMajority(arr, n); return 0; } |
5
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.