Question: C++ Problem Modify the program below by using dynamic arrays. Your program should prompt the user to input the number of candidates and then it

C++ Problem

Modify the program below by using dynamic arrays. Your program should prompt the user to input the number of candidates and then it creates the appropriate arrays to hold the information entered by the user (i.e., it declares a pointer of strings for the candidates and a pointer of integers for the number of votes received for each candidate).

Program:

#include

#include

#include

using namespace std;

// function prototype

int WinnerIndex(int votes[], int size);

void sumVotes(int votes[], double percentages[]);

void main()

{

// maximum size of the array

const int MAX = 5;

// parallel arrays for names of candidates,

string names[MAX];

int votes[MAX]; // number of votes received

double percentages[MAX]; // percentage of votes

double total = 0;

int winIndex;

string str;

// allow the user to enter the last names of five candidates in a local election and the number of votes received by each candidate

for (int i = 0; i < MAX; i++)

{

cout << " Enter the name of the candidate " << (i + 1) << ": ";

getline(cin, names[i]);

cout << "Enter the number of votes received by " << names[i] << ": ";

getline(cin, str);

votes[i] = stoi(str);

}

sumVotes(votes, percentages);

// get the winner index in the array by calling the WinnerIndex function

winIndex = WinnerIndex(votes, MAX);

// display each candidate's name, the number of votes received, and the percentage of the total votes received by the candidate.

cout << endl << left << setw(25) << "NAME_OF_CANDIDATE" << right << setw(15) << "VOTES_COUNT" << setw(15) << "PERCENTAGE" << endl;

for (int i = 0; i < MAX; i++)

{

cout << left << setw(25) << names[i] << right << setw(15) << votes[i] << setw(14) << setprecision(2) << fixed << WinnerIndex(votes, MAX) << "%" << endl;

}

// display the winner of the election

cout << " Winner of the election: " << names[winIndex] << " (" << votes[winIndex] << ")" << endl << endl;

system("pause");

}

// function implementation

int WinnerIndex(int votes[], int size)

{

int i, max, loc = 0;

max = votes[0];

for (i = 1; i < size; i++)

{

if (votes[i] >max)

{

max = votes[i];

loc = i;

}

}

return loc;

}

void sumVotes(int votes[], double percentages[]) {

double total = 0;

const int MAX = 5;

// compute the total number of votes

for (int i = 0; i < MAX; i++)

{

total = total + votes[i];

}

// compute the percentage of votes for each condidate

for (int i = 0; i < MAX; i++)

{

percentages[i] = votes[i] / total * 100.0;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!