while loops
An important feature of any programming language is the ability to perform an action repeatedly. This is known as “looping”. We may want to repeat a piece of code a finite number of times or until some condition is met; for example, the user typing in a value that signifies that the loop should terminate. In most cases, a boolean expression can be used to determine whether the loop continues or not.
A while
loop is one such looping construct. It repeatedly executes a statement or a block of code as long as a boolean expression is true. As soon as the boolean expression is false, the loop exits, and the next statement after the while
loop executes.
Figure 5.1 – The while loop syntax
In the preceding figure, we are assuming a block of code, hence the curly braces {}
. You could, of course, omit the curly braces {}
and the loop will just repeatedly execute one statement (which ends with a semi-colon). Interestingly, as the...