5.2 While Loops
The job of any loop is to perform iteration or repetition, and the simplest construct for doing this is known as a while loop. The general structure of a while loop is shown in Example 5-1. Its corresponding flowchart is shown in Figure 5-1.
1while(condition)2# statement 13# statement 24# ...5# statement n6end
The control flow enters the while loop at the instruction: while (condition). This statement determines
whether the control enters the body of the loop. If the condition
evaluates to true, then the statements within the loop are executed. If
the condition evaluates to false, then the control flow goes to the
instruction, end, and the loop is
exited. In the case where condition is
true, the control flow will continue
through all the statements between 1 and n, where
n is any number greater than 0. Once a statement has
finished executing, the control flow jumps back to the first instruction,
while (condition), and the whole
process starts over.
To clarify, a Ruby example is shown in Example 5-2. Its corresponding flowchart is shown in Figure 5-2.
1n=52i=03while(i<=n)4putsi5i=i+16end
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access