5.5 Infinite Loops

A classic problem, especially among new programmers, is that a small mistake can lead to implementing a program that simply will not stop.

Example 5-6 has an initial value of 5 stored in the variable i in line 3. The loop indicates that we should continue as long as i is greater than zero. Line 5 increments i. Hence, the loop condition of i > 0 is always true; so the loop will never terminate. When you run the program, it will look like nothing is happening, but in actuality, your computer is quite busy. It is happily repeating lines 4 and 5 forever. To terminate the program, hold down the Ctrl key and press C. This is an old key sequence that is an abbreviation for cancel, one of the arcane things you should memorize. (Ctrl-C cancels execution, and Ctrl-D ends the file.) There are a few other Ctrl sequences, but these two are all you need to make it through this book.

Example 5-6. Infinite loops
    1 puts "Count from 0 to ? "
    2 n = gets.to_i
    3 i = 5
    4 while (i > 0)
    5 	i = i + 2
    6 end

Assume you realize that you are in an endless loop, and you want to fix it. Sometimes new programmers simply execute the program again with no changes. Let us assure you that if you do not make a change, nothing will change. The program will once again run indefinitely.

The secret to fixing an endless loop is to check the terminating condition and make sure that it will ultimately be satisfied. Hence, change something but do not change things randomly. Identify the cause of the ...

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.