Infinite Loops

It is possible with most types of loops to create a condition that will always be true. Some conditions are simply always true, and others may be always true for a particular set of inputs. Such a condition causes what is called an infinite loop. A program with an infinite loop will continue to execute indefinitely, until it is killed (e.g. using Ctrl+C or the kill command in Unix).

Some infinite loops are intentional. We may want a program to continue monitoring inputs until the device is powered off, for example. This situation is often seen in robotics, home security systems, etc.

A common way to create an accidental infinite loop is by forgetting to add the housekeeping code to a do-while loop. When constructing a loop, we must take care to ensure that the condition will eventually become false.

Example 19.5. Infinite Loop

The loops below fail to update angle, and therefore continue to print sine(0) indefinitely.

! Initialization
angle = 0.0
final_angle = 360.0

! Condition
while ( angle <= final_angle )
    printf("sine(%f) = %f\n", angle, sin(angle * M_PI / 180.0));
! Initialization
angle = 0.0d0
final_angle = 360.0d0

! Condition
do while ( angle <= final_angle )

    ! Body
    print *, 'sine(',angle,') = ', sin(angle * PI / 180.0d0)

Sometimes it's obvious that an infinite loop is occurring, because of the output the program is producing. Other times, if the program is not producing output during the loop, it may be harder to detect.



Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What is a common cause of infinite loops?

  2. How do we terminate a process that's stuck in an infinite loop?