Introduction to Loops: The while Loop • Loop: a control structure that causes a statement or statements to repeat • General format of the while loop: while (expression) statement; • statement; can also be a block of statements enclosed in { }
The while Loop – How It Works while (expression) statement; • expression is evaluated – if true, then statement is executed, and expression is evaluated again – if false, then the loop is finished and program statements following statement execute
Watch Out for Infinite Loops • The loop must contain code to make expression become false • Otherwise, the loop will have no way of stopping • Such a loop is called an infinite loop, because it will repeat an infinite number of times
Using the while Loop for Input Validation • Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid.
• The while loop can be used to create input
routines that reject invalid data, and repeat until valid data is entered.
Counters • Counter: a variable that is incremented or decremented each time a loop repeats • Can be used to control execution of the loop (also known as the loop control variable) • Must be initialized before entering loop