Course contentsShow
← Computer Science
Lesson 178 of 2,8724. Introduction to ProgrammingFree lesson

Infinite Loops and Termination

Recognizing infinite loops, understanding why they occur, and ensuring loops terminate properly.

Infinite Loops and Termination

You'll learn how to recognize when a loop will never stop running and how to ensure your loops always terminate properly.

What Is an Infinite Loop?

An infinite loop is a loop that never stops executing because its condition never becomes false. Imagine you're told to keep walking forward until you reach a wall, but there is no wall—you'd walk forever! In programming, infinite loops happen when the loop control variable never changes in a way that makes the loop's boolean expression false.

Why Do They Occur?

The most common causes are:

  • Forgetting to update the control variable: If you set count = 0 and write while count < 10 but never change count inside the loop, it stays 0 forever.
  • Updating in the wrong direction: If count starts at 10 and you write while count > 0 but increase count each time, it will never reach 0.
  • Logic errors: Using the wrong comparison operator or flawed conditions.

Ensuring Proper Termination

Every loop needs three elements working together:

  1. Initialization of the control variable
  2. A condition that will eventually become false
  3. An update inside the loop that moves toward that false condition

Think of it like counting down to a rocket launch: you start at 10, check if you're above 0, and subtract 1 each time. Eventually you reach 0 and stop. If you forgot to subtract, you'd count "10, 10, 10..." forever.

Key Takeaway: Always verify that your loop control variable changes in a way that will eventually make the loop condition false—otherwise, your program will hang indefinitely.