Votes received by the candidate. Your program should also output the winner of t
ID: 3774656 • Letter: V
Question
Votes received by the candidate. Your program should also output the winner of the election. A sample output is: The Winner of the Election is Duffy. The input data should come from the file. Use 3 separate arrays to store the names, votes, and percentages before they are displayed. Include functions inputValues to input values for candidate names and votes received and place them in arrays. calcPercents which fills an array with the percentage of votes each candidate got. Determine Winner which returns the name of the winner. This function receives the percentage array and name array. Display Results which displays on the screen the output as shown. All arrays are declared in the main() function. Arrays must be passed to a function should the function need to process them.Explanation / Answer
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//function to display the array data
void displayResults(string name[],int votes[],float percentages[],int size)
{
int total=0;
cout<<"Candidate Votes Received % of Total Votes ";
for(int i=0;i<size;i++)
{
total+=votes[i];
cout<<name[i]<<" "<<votes[i]<<" "<<percentages[i]<<endl;
}
cout<<"Total "<<total<<" "<<total/size;
}
//function to detrmin winner and returns the winner name
string determineWinner(string name[],float percentages[],int size)
{
string mname="";
double max=0;
//loop through array and find the one with max votes
for(int i=0;i<size;i++)
{
if(max<percentages[i])
{
max=percentages[i];
mname=name[i];
}
}
return mname;
}
//function to calculate % of votes
void calcPercents(int votes[],float percentages[],int size)
{
int total=0;
for(int i=0;i<size;i++)
{
total+=votes[i];
}
for(int i=0;i<size;i++)
{
percentages[i]=(votes[i]*100)/total;
}
}
//function which reads votes data from file and stores them into array
int inputValues(string name[],int votes[])
{
int size=0;
ifstream myfile ("votes.txt");
if (myfile.is_open())
{
while ( myfile>>name[size] )
{
myfile>>votes[size];
size++;
}
myfile.close();
}
else
cout << "Unable to open file";
return size;
}
//main function which triggers the above funcitons
int main()
{
const int size=10;
string name[size];
int votes[size];
float percentages[size];
int length=inputValues(name,votes);
calcPercents(votes,percentages,length);
displayResults(name,votes,percentages,length);
cout<<" The Winner of the election is "<<determineWinner(name,percentages,length)<<endl;
return 0;
}
Sample Output:
Candidate Votes Received % of Total Votes
A 5000 28
B 4000 22
C 6000 34
D 2500 14
Total 17500 4375
The Winner of the election is C
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.