5.3 Until Loops

Gem of Wisdom

An infinite loop is a logic problem, not a syntax problem. Recall that syntax problems are things like misspelling else (try it sometime, and see what happens). Logic errors are much harder to fix, so take your time, trace the flow of execution, and step very slowly through the program.

The until loop is just the opposite of a while loop. Instead of occurring while some condition remains true, an until loop occurs until some condition becomes true. The code and semantics of the until loop are presented in Example 5-3. Its corresponding flowchart is shown in Figure 5-3.

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

Until loops execute the same way as while loops; the only difference is the way they terminate. If we want the counting program to work with until loops, only one line of the program needs to be changed: while(i <= n) becomes until(i > n). The until and while loops are logical opposites, and the change in the counting program illustrates this, as a greater-than conditional operator (>) is used instead of less than or equal to (<=). Table 5-1 shows every logical operator and its opposite operator.

Table 5-1. Logical operators and their opposites

Operator

Opposite operator

==

!=

>

<=

<

>=

Switching from a while loop to an until loop is easy; simply switch the operator in the condition to its opposite. However, this raises an interesting point: these loop constructs are interchangeable. There is never any case where you must use an until loop instead of a while loop, or vice versa. A Ruby programmer could go her or his entire life only knowing one of these loops and never have any problem writing any program.

At this point you are probably wondering why both loop types even exist. The reason for having both is to improve the clarity of a program. Some things are simply expressed in a clearer manner with while loops than with until loops, and vice versa. Instead of saying “while this is not true” we can say “until this is true,” and instead of saying “until this is not true” we can say “while this is true.” Frequently it is easier for someone to understand a program that simply tests for the existence of true instead of not true.

In the counting program from Example 5-2, the variable i is a counter. Using counters is common to many tasks that require automation. Anytime a given set of instructions needs to be executed a certain number of times, we will be using counters. Ruby actually does not require us to set up the counter at all. Instead, it is possible to give a set of numbers for a loop to iterate through.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.124.177