C++, using Visual Studio Redo program using dynamic arrays. You must ask the use
ID: 665072 • Letter: C
Question
C++, using Visual Studio
Redo program using dynamic arrays. You must ask the user for the number of candidates and then create the appropriate arrays to hold the data.
//header//
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//function declaration//
int voteamount(int list[], int size);
int wintally(int list[], int size);
//main start//
int main()
{
//variables//
string candidates[5];
int votes[5] = {0};
int totalVotes;
int i;
cout << fixed << showpoint;
//decimal precision//
cout << setprecision(2);
cout << "Enter candidate's name and the votes received by "
<<"the candidate." << endl;
for (i = 0; i < 5; i++)
//user input candidates//
cin >> candidates[i] >> votes[i];
//calculate sum of votes//
totalVotes = voteamount(votes, 5);
//print votes received//
cout << "Candidate Votes Received % of Total Votes" << endl;
for (i = 0; i < 5; i++)
cout << left << setw(10) << candidates[i]
<< right << " " << setw(10) << votes[i] << " " << setw(15)
<< (static_cast<double>(votes[i]) / static_cast<double>(totalVotes)) * 100
<< endl;
cout << "Total " << totalVotes << endl;
cout << "The Winner of the Election is "
<< candidates[wintally(votes, 5)]
<< "." << endl;
system("PAUSE");
return 0;
}
//method for vote amount//
int voteamount(int list[], int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
//calculates the sum of votes//
sum = sum + list[i];
//returns the value//
return sum;
}
//method for winner tally//
int wintally(int list[], int size)
{
int winInd = 0;
for (int i = 0; i < size; i++)
//checks list with the index value//
if (list[i] > list[winInd])
winInd = i;
return winInd;
}
Explanation / Answer
#include #include #include #include #include using namespace std; int main() { //variable declarations. //NOTE: pointer variables are declared later ofstream outfile; int array_size; double next, winner_votes(0), sum(0), percent; string candidate, winner_name; outfile.setf(ios::fixed); outfile.setf(ios::showpoint); outfile.precision(2); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); //opens output file outfile.open("results.txt"); if(outfile.fail()) { cout next; votes[i] = next; sum = sum + next; if(next > winner_votes) { winner_votes = next; winner_name = candidate; } } coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.