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 ...

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.