This is my print_winner function
void print_winner(void)
{
int winner_vote;
for (int i = 0; i < candidate_count; i++)
{
for(int j = i + 1; j < candidate_count; j++)
{
if(candidates[i].votes < candidates[j].votes)
{
winner_vote = candidates[j].votes;
}
else
{
winner_vote = candidates[i].votes;
}
}
}
for (int i = 0; i < candidate_count; i++)
{
if (winner_vote == candidates[i].votes)
{
printf("%s\n", candidates[i].name);
}
}
return;
}
My intention with the code- suppose there are 5 candidates- a,b,c,d,e. What I'm trying to do is first compare a to all the others & then b with all the others except a & the c with all the others except a & b & so on.
& this is the only error I got- print_winner did not print Alice as winner. But the thing is it passed every other case in check50. It printed all the single winner(except Alice) & all the winners if there was a tie. So then why isn't this code working for the Alice case?
I also found the following code which passed check50-
void print_winner(void)
{
int winner_vote;
for (int i = 0; i < candidate_count; i++)
{
for(int j = 0; j < candidate_count -i; j++)
{
if(candidates[i].votes < candidates[j].votes)
{
winner_vote = candidates[j].votes;
}
else
{
winner_vote = candidates[i].votes;
}
}
}
for (int i = 0; i < candidate_count; i++)
{
if (winner_vote == candidates[i].votes)
{
printf("%s\n", candidates[i].name);
}
}
return;
}
& I don't understand how the 2nd one is working.
So my questions are these-
Why is my code wrong? Why is it giving error in one of the single winner case when it passed all the other cases?
Why is the 2nd code correct?
PS- I found the 2nd case by trial & error.