Back to DFS's Workshop Page
Back to Agenda Page
Loops are used to execute a sequence of instructions repeatedly. In order to exit from a loop, we must have a method for checking to see if we have completed our task. To show this graphically, we can use a device called a flow chart.
A basic sort of loop is known as the do-while loop. This loop has the feature that the exit-condition check is built into the end of the loop.
// Print the first five Natural numbers
$num = 1;
do {
printf("%d\n", $num);
$num = $num + 1;
} while ($num <= 5);
Before the loop is begun, the counter called $num is initialized to the first value desired. The loop itself consists of four lines: (1) the reserved word do to indicate the beginning; (2) a statement to print the value of $num; (3) an assignment statement to increment the value of $num by one; and (4) the reserved word while with a condition inside parens to indicate the end. After each iteration of the statements inside the loop, the condition is checked. If the condition is false, the loop is exited. N.B. The statements inside the loop will ALWAYS be executed at least once, because the condition is not checked until after the statements have been executed.
// Print the first five Natural numbers
$num = 1;
while ($num <= 5)
{
printf("%d\n", $num);
$num = $num + 1;
}
Before the loop is begun, the counter called $num is initialized to the first value desired. The loop itself consists of five lines: (1) the reserved word while with a condition inside parens indicates that a set of statements is about to be specified; (2) {, an opening curly, to indicate the beginning; (3) a statement to print the value of $num; (4) an assignment statement to increment the value of $num by one; and finally (5) }, a closing curly, to indicate the end. Before each iteration of the statements inside the loop, the condition is checked. Only if the condition is true are the statements executed. N.B. This means that the statements inside the loop will NOT be executed even once if the condition is false when the initial check is made.