6. The While Loop Flashcards
while loops
WHILE some condition holds, DO something repeatedly
while loops syntax
while (condition)
action
or
while (condition) {
multiple statements
}
conditions and ;
no ; after the condition’s ) or after the closing }
what does a while loop cause
causes the body to be executed zero or more times
infinite loops
ensure loop body changes loop conditions to avoid infinite loops
correct while loops
1) initialise condition variables
2) test condition
3) modify condition variables
types of while loops
counter-controlled while loops
sentinel-controlled loops
flag controlled loops
counter-controlled while loops
syntax
counter = 0;
while (counter < N) { .... counter++; .. }
counter-controlled while loops
examples of uses
used for:
- read 20 numbers + average them
- printout value of investment for each of 35 years
note on counter-controlled while loops
we may prefer FOR loops instead that are to be executed a specific number of times
sentinel-controlled loops
syntax
cin»_space; variable
while (variable != sentinel) { .. cin >> variable; .. }
sentinel-controlled loops
examples of uses
add sequence of numbers terminated by 999
choosing sentinel
you can initialise the sentinel or input from user
flag controlled loops
syntax
found = false
while (!found) { . . if (expression) found = true; . . }
flag controlled loops
examples of uses
number guessing game