C++ project. Please write a program which repeatedly asks the user to enter vote
ID: 3829187 • Letter: C
Question
C++ project.
Please write a program which repeatedly asks the user to enter votes for different contestants in a game show and then outputs the winner and the number of votes s/he received. If more than one contestants received the same number of votes, the one which received the earliest vote wins. You can assume no more than 1000 votes will be cast. The user can enter "done" when there are no more votes to enter.
To get full points you must use at least two non trivial functions in your solution. The output for the winner must be printed in the main function. Your program must NOT have any global variables, use vector, or anything we have not seen in this course. Your code should be well structured and clean.
A sample run of the program is given below.
Enter a vote for: Alice
Enter a vote for: Bob
Enter a vote for: Bill
Enter a vote for: Jane
Enter a vote for: Bob
Enter a vote for: Jane
Enter a vote for: Bob
Enter a vote for: Mary
Enter a vote for: done
The winner is Bob with 3 votes.
Explanation / Answer
// Example program
#include <iostream>
#include <string>
using namespace std;
int unique(string votes[], int n, string unq[])
{
int count = 0;
for(int i = 0; i < n; i++)
{
int found = 0;
for(int j = 0; j < count ; j++)
{
if (votes[i] == unq[j])
found = 1;
}
if (! found)
unq[count++] = votes[i];
}
return count;
}
int getVotes(string votes[])
{
int i;
for(i = 0; i < 1000; i++)
{
cout << "Enter a vote for: ";
string vote;
cin >> vote;
if (vote == "done")
break;
votes[i] = vote;
}
return i;
}
int getVoteForCandidate(string votes[],int n, string candidate)
{
int count = 0;
for(int i = 0; i < n; i++)
{
if(votes[i] == candidate)
count++;
}
return count;
}
string getWinner(string votes[], int n, int &count)
{
count = 0;
string unq[1000];
int uniqCand = unique(votes, n, unq);
for(int i = 0; i < uniqCand; i++)
{
int vote = getVoteForCandidate(votes, n, unq[i]);
if (vote > count)
count = vote;
}
int voteCount[uniqCand];
for(int i = 0; i < uniqCand; i++)
{
voteCount[i] = 0;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < uniqCand; j++)
{
if(votes[i] == unq[j])
{
voteCount[j] += 1;
if(voteCount[j] == count)
return unq[j];
break;
}
}
}
return "";
}
int main()
{
string votes[1000];
int n = getVotes(votes);
int count = 0;
string winner = getWinner(votes, n, count);
cout <<"The winner is " << winner << " with " << count << " votes." << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.