Control Structures: Examples
Branching constructs can involve many kinds of comparisons among variables and constants of all types:
When an if
clause has only one statement, a shorter form may be used:
Here's an example of a more complicated logical expression with ordering:
Let's look at some loop examples. A do-loop does not need to have a loop variable (and boundaries) at all and may be exited at any time with the exit
statement. The exit
statement may be placed anywhere in the loop, most often within an if
statement. Placement at the end of the loop results in an until-loop, and placement at the beginning results in a while-loop. It may therefore be argued that the do-exit construct is more flexible than the usual do-while.
Example: Break from the loop anywhere
Example: Repeat until the condition is true
Example: Do while the condition is true
The exit
statement may also appear in a loop with a loop index:
Loop iterations may be skipped by using the cycle
statement. When a cycle
statement is executed, the next loop iteration is started immediately. In the example below, the variable x
is incremented 25 times, but the y
increment is skipped for the fifth iteration of the loop: