Difficulty with code question in C language

For the 3rd Problem Set at Harvard's EdX class, I'm having trouble figuring out how I'm supposed to store variables, if the variable would have the same name.

Like I want to check if candidates[i].votes is bigger the 1st time, than the 2nd time, than the 3rd time, etc. and I'm not sure about how I'd go about coding that myself? Any insight would be great.

​

https://cs50.harvard.edu/college/psets/3/plurality/ is the problem set;

and

void print_winner(void)

{

string winner;

int previousvote = 0;

for (int i = 0; i < candidate_count; i++)

{

previousvote = candidates[i].votes;

if (candidates[i].votes > previousvote)

{

winner = candidates[i].votes

}

else (candidates[i].votes == winner)

{

}

​

is my code.

​

Any help would be appreciated!

Posted Sep 28, 2019, 9:11 PM UTC

02
quarentaedois•

You have to find the greatest element in an array. Start with this variable:

int winner = 0;

That is, assume the candidate with index 0 is the winner. It's a guess.

Then search the rest of the array. Compare the number of each candidate with i=2,3,4,... against the "winner". If the i-th candidate has more votes than the one you guessed, update your guess.

if (candidates[i].votes > candidates[winner].votes) {
}

You'll have to complete this if to update your guess.

After the for loop, you'll have checked everyone and winner will be the index of the elected candidate. Then you can print their name.

3
bpeempOP•

Man. You're brilliant.

1