What if the expression of a while loop never evaluates to false? In this case the program will loop over and over again until you physically stop it. Programmers call this an infinite loop. We can simulate this by using the keyword true as an expression. True represents what it says it will never become false.
Run the program
When you are satisfied that the program will never end, use the break button to stop it
There is also a false keyword. It always evaluates to false and will never become true.
Change the keyword true in the while loop to the keyword false
Run the program
Note how the instructions in the loop are never performed
Sometimes it is more convenient to program an expression that evaluates to the opposite of what we want and then tell the compiler we want the opposite again. We do this with the ! symbol and we place it before the expression we want the opposite of. ! turns a true expression into a false one, and a false one into a true one. Programmers call this symbol a not, so when you see the expression !true you can pronounce it as not true.
| This expression | Is the same as |
|---|---|
| true | true |
| !true | false |
| false | false |
| !false | true |
Put a ! in front of the expression false in the while loop, so it looks like this: while( ! false )
Run the program again. You will have to break the program to stop it.
There are other sorts of expressions that cause an infinite loop, we dont have to explicitly state that an expression is true. All we need is an expression that is true and can never become false. For example we could use the expression 1 == 1. One is equal to 1, so this is true. 1 can never be equal to anything other than 1, so the expression will never change.
Try out the following expressions in the while loop to see what they do. Try and work out what they do before you run the program.
1 == 1
1 == 2
!! true