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.
Entrance
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.
Exit
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.
Example
Entrance:
3 10
1 3 2 1 2 3 3 3 2 2
Exit:
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;
sum=0;
cin>>c>>v;
for(p=1;p<=v;p++)
cin>>tab[p];
for(int i=1;i<=c;i++){
if (i==tab[p]){
sum+=tab[p]+1;
}
cout<<i<<": ";
cout<<sum<<endl;
}
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.
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;
++votesPerCandidate[currentVote];
}
for (int candidateCount = 0; candidateCount < candidateAmount ; ++candidateCount)
{
cout << candidateCount + 1 << ": "
votesPerCandidate[candidateCount] << endl;
}
return 0;
}