Session 5: Booleans and breaks

Using the boolean type (Section 4.5)
break statement (Section 4.8)
Exercise

Using the boolean type

Textbook: Section 4.5

The boolean type is a bit odd. We use it quite a bit when we're programming, but it's not often that you think about it. For example, the expression i < n computes a boolean value. But generally we just put these expressions to compute a boolean value as the condition to an if or a while statement.

But sometimes it's useful to have a variable that holds a boolean value. Such a variable is generally called a flag. For example, quite often you might use a flag to indicate when it's time to stop running through a loop.

boolean has_guessed = false;
while(!has_guessed) {
    IO.println("Guess a number. ");
    if(IO.readInt() == 32) has_guessed = true;
}
IO.println("You got it!");
In this example, we repeatedly ask the user to guess a number, until at last the user guesses 32. When the user guesses 32, the computer sets the has_guessed flag to true, which prevents the program from going through the loop again.

It's tempting to write something like the following.

while(has_guessed == false) { //...
This has the same effect as while(!has_guessed), but the style is worse - it's wordier, and it doesn't read as nicely.

Notice that we could have avoided the if statement in our loop.

while(!has_guessed) {
    IO.println("Guess a number. ");
    has_guessed = (IO.readInt() == 32);
}
This works because the != operator computes a boolean, which we can simply place into the has_guessed flag.

break statement

Textbook: Section 4.8

The break statement is useful when you want to immediately terminate from a loop. In fact, in our has_guessed example, we could have used a break statement instead.

while(true) {
    IO.println("Guess a number. ");
    if(IO.readInt() == 32) break;
}
IO.println("You got it!");
This works the same way: It continues asking the user to guess a number, until finally the user types 32. When the user types 32, the computer executes the break statement, which breaks out of the while loop and continues with the following statements.

Exercise