0

Could anyone perhaps help me figure out what's wrong with the code below? When I check it manually, it works every time, in every scenario I can think of, but when I run check50 on it, I get ":( print_winner identifies Charlie as winner of election Cause print_winner function did not print winner of election". Everything else works fine. Even printing my sorted list seems to show that my sort function is working well.

I later realized I don't have to actually sort this list to perform the print_winner() function; I changed it to simply identify the highest vote count and print all candidates with that vote count. This solved the issues with check50, but I still want to know what's wrong with my original code. Here's my original print_winner() function in full:

void print_winner(void)
{
    
    //Sort the candidates by number of votes (I'm just using a "reverse" bubble sort since the max number candidates is 9)
    for (int i = 0; i < candidate_count - 1; i++)
    {
        //If the a candidate has fewer votes than the next, swap votes, keep swapping until the next candidate has fewer votes
        for (int j = 1; j < candidate_count - i; j++)
        {
            if (candidates[i].votes < candidates[i + j].votes)
                {
                    candidate store = candidates[i];
                    candidates[i] = candidates[i + j];
                    candidates[i + j] = store;
                    j++;
                }
        }
    }
    
    //With the now sorted list, print the candidate with the highest vote
    int i = 0;
    do
    {
        //Keep printing until the next candidate has fewer votes than the printed
        printf("%s\n", candidates[i].name);
        i++;
    }
    while (candidates[i -1].votes == candidates[i].votes);
}
2
  • Try an election with 3 candiates a b c and 6 voters; votes cast a, b, b, c, c, c to aid with debugging/troublshooting. Jun 4, 2021 at 21:04
  • Thanks a lot! This helped me to solve the problem; I had an extra line of j++ in the sorting loops. Jun 8, 2021 at 7:31

0

You must log in to answer this question.

Browse other questions tagged .