Also, main function should consist of only function calls and variable declarati
ID: 3834946 • Letter: A
Question
Also, main function should consist of only function calls and variable declarations. There should be NO loops or if statements in the main. 7. Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should then output each candidate's name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. A sample output is: Candidate Votes Received of Total Votes 25.91 5000 Johnson 20.73 4000 Miller 6000 31.09 Duffy 12.95 2500 Robinson 9.33 1800 Ashton y 19300 Total The winner of the Election is Duffy.
Explanation / Answer
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void getVotes(string candidates[], int votes[], int n)
{
for(int i = 0; i < n; i++)
{
cout << "Enter candidate " << (i+1) << "'s last name: ";
cin >> candidates[i];
cout << "Enter votes received by " << candidates[i] << " : ";
cin >> votes[i];
}
}
int getTotal(int votes[], int n)
{
int total = 0;
for(int i = 0; i < n; i++)
{
total += votes[i];
}
return total;
}
int getWinner(int votes[], int n)
{
int max = votes[0];
int max_index = 0;
for(int i = 1; i < n; i++)
{
if(max < votes[i])
{
max = votes[i];
max_index = i;
}
}
return max_index;
}
double getPercentage(int vote, int total)
{
return (((double)vote)/total)*100.0;
}
void printResults(string candidates[], int votes[], int n)
{
cout << "Candidate Votes Received % of Total Votes" << endl;
int total = getTotal(votes, n);
for(int i = 0; i < n; i++)
{
cout << candidates[i]<< " " << votes[i] << " "<<fixed << setprecision(2) << getPercentage(votes[i], total) << endl;
}
cout << "Total "<< total << endl;
cout << endl;
cout << "The Winner of the Election is " << candidates[getWinner(votes, n)] << endl;
}
int main()
{
string candidates[5];
int votes[5];
int n = 5;
getVotes(candidates, votes, n);
printResults(candidates, votes, n);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.