In: Computer Science
Write a C++ program using dynamic arrays that allows the user to enter the last names of the candidates in a local election and the number of votes received by each candidate. The program must ask the user for the number of candidates and then create the appropriate arrays to hold the data. 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. (20 points) A sample output is: Name of Candidate Votes Received % of Total Votes Ali 5000 25.91 Imran 4000 20.73 Ahmad 6000 31.09 Ijaz 2500 12.95 Khan 1800 9.33 Total 19300 The winner of the local election is Ahmad.
C++ PROGRAM ===>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout<<"Enter number of candidate : ";
cin>> n;
string name[n]; // array of n size to store last name
int vote [n]; // array of n size to store received vote
int total_vote=0;
for(int i=0;i<n;i++)
{
cout<<"Enter candidate name : ";
cin>>name[i];
cout<<"Enter vote : ";
cin>>vote[i];
}
// for loop to calculate total vote
for(int i =0;i<n;i++)
{
total_vote = total_vote+vote[i];
}
int max = vote[0];
int k,index;
// calculate index of maximum in vote array
for(k=0;k<n;k++)
{
if(vote[k]>=max)
{
max = vote[k];
index = k;
}
}
cout<<endl<<endl;
double percentage;
cout<<left<<setw(35)<<"Name of candidate
"<<left<<setw(15)<<
"Vote"<<left<<setw(15)<<"Received %
"<<endl;
for(int i=0;i<n;i++)
{
percentage = vote[i]*100.0/(total_vote*1.0); // calculate vote
percentage
cout<<left<<setw(35)<<name[i]<<left<<setw(15)<<vote[i]<<left<<setw(15)<<fixed<<setprecision(2)<<percentage<<endl;
}
cout<<endl<<"Total vote :
"<<total_vote<<endl;
cout<<"The winner is
"<<name[index]<<endl<<endl;
return 0;
}
OUTPUT SCREENSHOT ===>