鶹Լ

Condition-controlled loops - infinite loops

Sometimes when using a condition-controlled (WHILE) loop there may be a situation where the program loops forever. This situation is known as an infinite loop.

How do infinite loops occur?

Condition-controlled loops have a condition that is tested at the start of the iteration to determine whether or not the iteration should occur. With each iteration, the condition is tested again. As long as the condition is being met (ie is true), the iteration continues. If the condition is never met, then the program loops infinitely.

Consider this simple algorithm to count up in twos from one to a hundred:

  1. set value of count to 1
  2. while the value of count does not equal 100
  3. say the value of count
  4. add 2 to the value of count
  5. otherwise, stop

The Python (3.x) program would look like this:

count = 1
while count != 100:
	print(count)
	count += 2

The program works like this:

  • the variable ‘count’ is set to 1
  • the ‘while’ statement specifies where the iteration begins
  • the value of ‘count’ is output
  • the value of ‘count’ is increased by 2
  • the program iterates as long as the condition ‘count does not equal 100’ is true

This program will appear to run correctly but, because the condition ‘count does not equal 100’ is always true, the iteration will occur infinitely. This is because the value of count, which will always be an odd number, will never equal 100.

Infinite loops can cause programs to fail, because the program gets stuck repeating a section of code over and over. However, infinite loops can also be used to ensure a program does run forever, for example the program that controls a traffic light.