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.

Example 5-1. While loop construct
    1 while (condition)
    2 	# statement 1
    3 	# statement 2
    4 	# ...
    5 	# statement n
    6 end
While loop flowchart
Figure 5-1. While loop flowchart

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.

Example 5-2. Counting program
    1 n = 5
    2 i = 0
    3 while (i <= n)
    4 	puts i
    5 	i = i + 1
    6 end
Counting program flowchart
Figure 5-2. Counting program flowchart ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.