Candidate Program

This is what i have so far, but i am not too sure how to input the percentage of the total votes received by the candidate. Here is the assignment Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. 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. I really would appreciate the help. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string> 
#include <iomanip> 

using namespace std;

class Candidate {
public:
	string lastName;
	int numVotes;
};

int main() {

	

	Candidate election[5];

	for (int i = 0; i<5; i++) {

		cout << "Please enter the last name of candidate #" << i + 1 << ": ";
		cin >> election[i].lastName;
		cout << "How many votes did : " << election[i].lastName << " Receive? : ";  
		cin >> election[i].numVotes;
	}

	for (int i = 0; i<5; i++) {
		cout << setw(7) << election[i].lastName;
		cout << setw(7) << election[i].numVotes;
		cout << endl;
	}

	

	int max = election[0].numVotes; 
	string winner = election[0].lastName;

	for (int i = 1; i<5; i++) {
		if (election[i].numVotes > max) {
			max = election[i].numVotes;
			winner = election[i].lastName;
		}
	}

	cout << "The winner of the election was " << winner << " had " << max << " votes." << endl;
	
system("Pause");
}
Last edited on
percentage like 5% for first candidate and stuff ?
correct me if i'm wrong sum up all of numvote from every candidate lets say we put it to sum, then for each candidate divide their numvotes with sum and multiply with 100
yes that is correct i just don't know how to add that to the code. So basically say the first candidate had 10 votes and the 2nd had 20 and the third had 5 and the 4th had 15 and the fifth had 25 add the votes up than display what each percentage of votes the candidate had compared to the other candidates.
if your storing the last names in election[i].lastName then it should
just be a cout << election[i] << endl;

the dot operator works right to left.

if you want to input the percentage... you need something other then i to store the variable...
election[j].numVotes

whatever is in these [] is an index.... so .... if different value... then different index...

cheers!
Im still pretty lost on how to and where to input this into the code. Sorry im really new to c++ and its becoming the death of me.
Well you know how to itterate through the array, its pretty much the same to sum. You can count sum and find percentage in seperate for statement after input, or find sum along with the input
Topic archived. No new replies allowed.