While Loops: Repeat Until Done

Indefinite Iteration

Part of: Algorithms, Iteration & Simulation

Iteration means repeating a block of code. When you do not know in advance how many repetitions you need, you only know a condition for stopping, you reach for a while loop . This is indefinite iteration . Anatomy of a while loop A while loop repeats as long as its condition is True. Each pass: 1. Check the condition. If False, exit the loop. 2. If True, run the body. 3. Return to step 1. The key detail is the update : n = n - 1 changes the variable the condition depends on. Without it the condition would stay True forever. The infinite loop trap If the body never makes the condition False, you get an infinite loop : the program runs forever: Every while loop needs three things: a starting value, a condition, and an update inside the body that drives the condition toward False. A real example: the Collatz steps The Collatz process takes a number and repeats: if even, halve it; if odd, triple it and add one. It always reaches 1, but the number of steps is unpredictable, perfect for a while loop: You cannot know the step count ahead of time, so a counted loop will not do, but the condition n != 1 tells you exactly when to stop. Why it matters While loops handle the open-ended repetit

Challenge: Collatz Steps