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

c++ program Please write a program which repeatedly asks the user to enter votes

ID: 3827457 • Letter: C

Question

c++ program

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.

Enter a vote for: Aurora
Enter a vote for: Jill
Enter a vote for: Jill
Enter a vote for: Dave
Enter a vote for: Max
Enter a vote for: Sarah
Enter a vote for: Max
Enter a vote for: Jill
Enter a vote for: done
The winner is Jill with 3 votes

Explanation / Answer

Below is the code followed by output.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){
   int n;
   cout << "Enter the number of contestants: " ;
   cin >> n;
   cout << "Enter the names of contestants: " ;
   vector<string> v;
   string temp;
   for(int i =0; i<n; i++){
       cin >> temp;
       v.push_back(temp);
   }
   cout << "Cast your votes now: " ;
   int array[n] = {0};
   int counter = 0;
   int c_arr[n];
   while(1){
       cout << "Enter a vote for: " ;
       cin >> temp;
       if( temp.compare("done") == 0){
           break;
       }
       int curr;
       for(int i =0; i<n; i++){
           if(v[i].compare(temp) == 0){
               curr = i;
               break;
           }
       }
       counter++;
       array[curr] = array[curr]+1;
       c_arr[curr] = counter;
   }

   int max_count = 0;
   string winner;
   int prev_c = 1000;
   for(int i=0; i<n; i++){
       if(max_count < array[i]){
           max_count = array[i];
           winner = v[i];
           prev_c = c_arr[i];
       }
       if(max_count == array[i]){
           if(c_arr[i] < prev_c){
               prev_c = c_arr[i];
               winner = v[i];
           }
       }
   }

   cout << "The winner is " << winner << " with " << max_count << " votes." << endl;
}

Output:

Enter the number of contestants: 3
Enter the names of contestants: ham
sam
dam
Cast your votes now: Enter a vote for: sam
Enter a vote for: dam
Enter a vote for: sam
Enter a vote for: dam
Enter a vote for: ham
Enter a vote for: done
The winner is sam with 2 votes.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote