Stephan Stephan - 1 year ago 73
C++ Question

Voting Program CPP help (wrong output)

First of all thanks for reading. The program I am trying to write has to do following:

In the elections of the mayor of the Great Guslaru took off M candidates labeled by numbers from 1 to M. Each of the N voters gave an important vote for one of them.
Write a program that reads the description votes, and then give the results of voting and number of the selected candidate for mayor.
According to the electoral law of the Great Guslaru, if two or more candidates received the same, the highest number of votes, the election is won by the one who has a lower number.


First line of input contains two integers M and N (1 <= M <= 10, 1 <= N <= 1000), determining the appropriate number of candidates and the number of votes cast.
The second line is N integers from 1 to M. These are the numbers of candidates, which were given to individual voices.


In the first M lines, output should be given in sequence number of votes won by candidates with numbers from 1 to M, in the format "X: Y",
where X is the number of the candidate, and Y - the number of votes cast for it. Then a separate line should contain the number of the candidate who won the election.



3 10

1 3 2 1 2 3 3 3 2 2


1: 2

2: 4

3: 4

The code I have right now is:

#include <iostream>

using namespace std;

int main()
int c,v,tab[100],sum,p;

for(int i=1;i<=c;i++){

if (i==tab[p]){
cout<<i<<": ";
return 0;


My output is as following:

1: 0

2: 0

3: 0

I have figured out so far that all it seems to do is take and output the sum. Any tips or advice? Thanks.

pvl pvl
Answer Source

Disclaimer I haven't tested this

First of all, you should work be a little more neatly with your code. Give proper self-explanatory names and use indentation to show loops more clearly.

#include <iostream>
using namespace std; 

int main() 

Initialise variables on their own line and give them informative names.

   int candidateAmount;
   int voteAmount;

   cin >> candidateAmount
       >> voteAmount;

Arrays are zero-based in c++. A 100 element array will run thus from index 0 to 99.

   int votes[voteAmount];
   int votesPerCandidate[candidateAmount];
   for (int voteCount = 0; voteCount < voteAmount; ++voteCount) 
     int currentVote = 0;
     cin >> currentVote; 
     votes[voteCount] = currentVote;

   for (int candidateCount = 0; candidateCount < candidateAmount ; ++candidateCount)
       cout << candidateCount + 1 << ": " 
       votesPerCandidate[candidateCount] << endl;
    return 0; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download