C++ project. Please write a program which repeatedly asks the user to enter vote
ID: 3830039 • 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
// C++ code
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string names[1000];
string str;
int countArray[1000] = {0};
int size = 1;
cout << "Enter a vote for: " ;
cin >> names[0];
while(1)
{
cout << "Enter a vote for: " ;
cin >> names[size];
if( names[size].compare("done") == 0)
{
break;
}
size++;
}
int visited[1000] = {0};
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
if(names[i].compare(names[j]) == 0 && visited[j] == 0)
{
countArray[i]++;
visited[i] = 1;
}
}
}
int max = countArray[0];
string maxStr = names[0];
for (int i = 1; i < size; ++i)
{
if(countArray[i] > max)
{
max = countArray[i];
maxStr = names[i];
}
}
cout << "The winner is " << maxStr << " with " << max << " votes." << endl;
return 0;
}
/*
output:
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.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.