okaay, you'll need 2 arrays. One will hold the names of the candidates that is, string array, and the other will hold their votes so it's of type integer
first you get the number of candidates :
int n = 0;
do
{
cout<<"\nEnter the number of candidates [2-10] : ";
cin>>n;
} while(n<2 || n>10)
after getting the number of of candidates n, and performing the basic test to it to ensure it is within 2 and 10, you need to define the containers that will hold the data :
string names[n];
int votes[n];
these two lines defines the required two arrays.Also, for the votes percentage purpose you'll need the total number of votes. so we'll define a variable for this task and its value will increase in the entering data step:
int totalVotes = 0;
The next step is to ask the user to enter the required data one by one. each record consists of two fields : name and votes :
for (int i = 0; i < n; i++)
{
cout<<"\nCandidate number "<< (i+1) ;
// get the candidate name
cout<<"\nEnter the name :";
cin>> names[i];
// get the candidate votes
cout<<"\nEnter the number of votes :";
cin>> votes[i];
// add that number of votes to the total number of votes
totalVotes = totalVotes + votes[i];
}
now you know how to declare arrays and to assign values to it's elements. Next we'll see how to retrieve the values from these arrays and make use of it like this :
cout<<"\n***************************************************\n";
for (int i = 0; i < n; i++)
{
cout<<"\nCandidate number "<< (i+1) ;
// output candidate's name
cout<<"\nName : " << names[i];
// output the candidate's percentage votes
cout<<"\tPercentage votes : "<< votes[i] / totalVotes * 100;
}
finally to output the winner, we'll sort the votes array and get the maximum element of it like this :
for (int i = 0; i< n; i++)
for (int j = i; j < n; j++)
if ( votes[i] < votes[j] )
{
// sawp the votes array elements
int tempVotes = votes[i];
votes[i] = votes[j];
votes[j] = tempVotes ;
// you need to make the same changes to the names array to keep the correspondence between names and votes
string tempName = names[i];
names[i] = names[j];
names[j] = tempName;
} // enf if, for j, for i
// now votes array is sorted in descending order, the max is the first
cout<< "\n\nThe Winner is : "<
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.