-1

I have a loop that looks something like this

int temp = 0; 
int menuItem;
while (temp != -1 && temp < 5)
{
    cout << "Order " << temp + 1 << ": ";
    cin >> menuItem;
    arrayData[temp] = menuItem;
    temp++;
    break;
}

When I learned to use sentinels, I did not learn them using break... for example.

int total = 0;
int points;
int game = 1; 

cout << "Enter the points for game #" << game << endl;
cin >> points;

while (points !=-1)
{
    total += points;

    game++;
    cout << "Enter the points for game #" << game << endl;
    cin >> points;
}

This second loop continues on towards infinity until the value -1 is entered, and then it stops without the need for a break;. My first loop however will not stop when the sentinel value is entered unless the break is included.

Why is that?

Podo
  • 709
  • 9
  • 30
  • Your first loop exits based on `temp` but your input is `menuItem`. Therefore, input of `-1` does nothing – kmdreko Mar 08 '16 at 23:19
  • I'm not exactly clear what you're asking. When you stepped through the code, how did it differ each time? Loops just check the condition each time, so you must be changing the values tested in the condition – TankorSmash Mar 08 '16 at 23:20
  • under what condition do you expect that loop to terminate? It will keep going till temp == 5 – pm100 Mar 08 '16 at 23:21

2 Answers2

2

While statement always repeat until the set condition get to false. In your first code example

while (temp != -1 && temp < 5)

Here, the while loop will exit if temp is -1 or temp is equal to 5. But, you insert break in your code which is will stop or force your while loop condition to stop.

while (condition) {
    // Some code.

    // Even if the condition true, it will stop because of break.
    break;
}

In your second code, the condition set to

while (points !=-1)

so the while will only stop or exit, if the points variable has value of -1.

After understand the basic, you will find the answer for your question on why on the first while it didn't stop if there is no break;. The answer is because the condition on that while is still true so that the while execute again.

AchmadJP
  • 893
  • 8
  • 17
1

break always breaks the loop when it´s called.

In your first loop, however, you´re reading menuItem, no temp.

So, if you in enter -1 menuItem equals -1, no temp.

  • I still don't see then why it runs in the first place. Wouldn't it break after the first iteration of the loop? This loop will run 1-5 times, but only breaks when the sentinel value is entered. – Podo Mar 08 '16 at 23:22
  • Ok, it runs in first place because temp = 0, so is temp != -1 ? true. Is temp < 5 ? true. So the condition evaluates to true and the first cicle of the 'while' is executed. Then the program sees instruction 'break' at the end of the cicle, so it gets out of the loop with just the first cicle, no more. – Andrés Guerrero Mar 08 '16 at 23:29