0

I am doing Problem Set 3 Plurality. I am currently on the print_winner function. My program compiles but I'm having issues because it does not print the winner and any ties it prints whoever got the least amount of votes way too many times and prints alot of "nulls" while its doing it. I assume my problem is with either my sorting algorithm or with how I was trying to use recursion. i also created my own placeholder "candidate" to do the switching in the array im not sure if that is effecting anything. Thanks for any advice!

Code:

// Update vote totals given a new vote
bool vote(string name)
{
    // TODO
    int amount = 0;
    for (int x = 0; candidates[x].name != NULL; x++)
    {
     if (strcmp(name, candidates[x].name) == 0)
     {
         candidates[x].votes++; amount++;
     }
    }
    if (amount == 0)
    return false;
    else return true;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
   //Create a counter mechanism

       int counter = 0;
    // for loop to iterirate through
   for (int i = 0; i < candidate_count - 1; i++ )
   {

   //compare two numbers
        if (candidates[i].votes > candidates[i+1].votes)
   // create placeholder
        {

            candidate ph;
    //sort if incorrect and add one to the counter

            ph = candidates[i];
            candidates[i] = candidates[i+1];
            candidates[i+1] = ph;
            counter++;
        }

        if (counter > 0)
        {
            print_winner();
        }

        else

        {
            printf("%s \n", candidates[candidate_count].name);
        }

        for (int z = 0; candidates[z].name != NULL; z++)
        {
            if (candidates[z].votes == candidates[candidate_count].votes)
            {
                printf("%s \n", candidates[z].name);
            }
        }
   }
    return;
}

I only include the portions of the code I edited for the assignment.

You must log in to answer this question.

Browse other questions tagged .