0

I know break statements are pretty basic, but it's got me here:

This is my function:

for (int i = 0; i < voter_count; i++)
{
    for (int j = 0; j < candidate_count; j++)
    {
        if (candidates[preferences[i][j]].eliminated == false)
        {
            candidates[preferences[i][j]].votes++;
            break;
        }
    }
}
return;

Now, it works perfectly. But if i remove the break; it will not give the correct output! Can someone please clarify what exactly is break; doing here. I mean i have worked with some program mes involving loops, but never experienced this!

Thank You

1

Each round counts one vote per voter, for their top preferred, non-eliminated candidate. Once that vote is counted, program moves on to the next voter. From the C99 standard section 6.8.6.3:

A break statement terminates execution of the smallest enclosing switch or iteration statement.

In this case it terminates the the j loop and moves on to the next voter, ie the i loop.

1
  • Ah, yes... Thank you very much for clarifying that – Musical_Ant Mar 12 '20 at 16:01
0

Thank you very much for your question! I've been struggling that very "break"!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .