Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. (100 pts) Write a program that finds the majority element in an array if it e

ID: 3760489 • Letter: 1

Question

1. (100 pts) Write a program that finds the majority element in an array if it exists. Majority element is the element which appears in more than half of the array locations. Declare an array of size 7 and read the array elements from the user. Then, compute and print the majority element if it exists. In an array of size 7, an element has to appear in at least 4 array locations in order to be majority element. Consider the following example. Majority element in this array is 3 since 3 appears 4 times and array size is 7 (0-6). Sample execution of the program for this array is given below Enter 7 numbers In some cases majority element does not exist. Following example shows this. There is no majority e1ernent in this array. Maximum count in the array is 2. However, 4 is needed for majority. Sample execution of the program is given below Enter 7 numbers No Majority One approach to this problem is to count how many times each element appears in the array. Find the maximum occurrence and compare it with 4. If maximum occurrence in the array is greater than equal to 4 then corresponding element is majority. If maximum occurrence is

Explanation / Answer

Here is the sample code for you. If you have any further queries, just get back to me.

#include <iostream>
using namespace std;

int Count(int Array[], int x)   //Counts the number of times x appears in the Array.
{
int c = 0;
for(int i = 0; i < 7; i++)
{
if(Array[i] == x)
c++;
}
return c;
}
int Majority(int Array[])   //Finds the majority element in the Array.
{
int c;
for(int i = 0; i < 4; i++)   //For the first 4 elements.
if((c = Count(Array, Array[i])) > 3)   //Counts the number of times, that element appears in the array.
return Array[i];                   //If count is greater than 3, returns that element.
return -1;                             //If no element count is greater than 3, finally returns -1.
}
int main()
{
int Array[7], majorityNumber;
cout<<"Enter 7 elements into the array: ";  
for(int i = 0; i < 7; i++)   //Reads 7 elements into the array.
cin>>Array[i];
majorityNumber = Majority(Array); //Calls the function Majority().
if(majorityNumber == -1)   //If the function returns -1, there is no majority element.
cout<<"There is no majority element in the array."<<endl;
else       //Else the returned element itself is the majority element.
cout<<"Majority = "<<majorityNumber<<"."<<endl;
}