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

2 Answers 2

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 Mar 12, 2020 at 16:01
0

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

3
  • 1
    This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review May 25, 2021 at 11:44
  • This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review
    – Cliff B
    Jun 16, 2021 at 22:24
  • Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful. - From Review Sep 18, 2021 at 23:50

You must log in to answer this question.

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