How Loops Work: Repeating Actions with Blocks, for, and while in Python & C++
Master counted loops and condition-controlled loops across visual blocks, Python, and C++, and learn how to trace loop counters to prevent off-by-one bugs and infinite loops.
In This Article
- Apply the DRY (Don't Repeat Yourself) principle using loop control structures.
- Choose accurately between counted loops (for) and condition-controlled loops (while).
- Build a loop trace table to inspect how variables change on every iteration.
- Prevent infinite loops and off-by-one boundary errors in Python and C++.
Why Do Programs Need Loops?
Imagine you are writing a program to send a welcome notification to 500 new students, or to check every pixel in a 1920×1080 image. Without loops, you would have to copy and paste the same instruction hundreds or millions of times. Worse yet, if you needed to change how the message was formatted, you would have to edit every single copy by hand.
In software engineering, this violates a core rule known as DRY: Don't Repeat Yourself. Whenever a program needs to perform the same action—or a predictable pattern of actions—multiple times, we wrap those instructions inside a loop. Each pass through the body of a loop is called an iteration.
The Two Families of Loops: Counted vs. Condition-Controlled
Nearly all programming languages provide two main types of loops. Choosing the right one depends on a single question: Do you know in advance how many times the loop needs to run?
1. Counted Loops (repeat N times / for)
Use a counted loop when the number of iterations is known before the loop starts—for example, "repeat 10 times," "count from 1 to 100," or "process each of the 12 months in a year."
- Visual Blocks: Uses a
repeat 4 timesblock or acount with i from 1 to 4block. - Python: Uses
for i in range(4):. By default, Python'srange(4)generates four numbers starting at zero:0, 1, 2, 3. You can also specify a start and stop value usingrange(1, 5), which counts1, 2, 3, 4(stopping just before 5). - C++: Uses a three-part header:
for (int i = 0; i < 4; i++).- Initialization (
int i = 0): Creates the counter variable once when the loop begins. - Condition (
i < 4): Checked before every iteration; as long as it is true, the loop body runs. - Update (
i++): Adds 1 toiat the end of each iteration.
- Initialization (
Visual Block Logic
SET sum TO 0
COUNT WITH i FROM 1 TO 4 BY 1
SET sum TO sum + i
PRINT sum
Python
total = 0
for i in range(1, 5):
total = total + i
print(total)
C++
int total = 0;
for (int i = 1; i <= 4; i++) {
total = total + i;
std::cout << total << "
";
}
Tracing the Loop Step by Step
Beginners often try to guess what a loop does all at once. Professional programmers use a trace table to track the value of each variable at the end of every iteration. For the code above, our trace looks like this:
- Before loop starts:
total = 0 - Iteration 1 (
i = 1):totalbecomes0 + 1 = 1→ prints1 - Iteration 2 (
i = 2):totalbecomes1 + 2 = 3→ prints3 - Iteration 3 (
i = 3):totalbecomes3 + 3 = 6→ prints6 - Iteration 4 (
i = 4):totalbecomes6 + 4 = 10→ prints10 - After Iteration 4:
ireaches5, the condition fails, and the loop terminates.
2. Condition-Controlled Loops (while / repeat until)
Sometimes you do not know in advance how many iterations will be needed. For example, how many times must a player roll a die until they get a 6? Or how many times can you halve a number before it drops below 1? For these situations, we use a while loop.
A while loop checks a boolean (true/false) condition before every pass. As long as the condition evaluates to true, the loop body executes, then jumps back up to test the condition again. As soon as the condition becomes false, the program skips past the loop and continues with the rest of the code.
Visual Block Logic
SET fuel TO 100
SET laps TO 0
WHILE fuel >= 25 DO
SET fuel TO fuel - 25
SET laps TO laps + 1
PRINT laps
Python
fuel = 100
laps = 0
while fuel >= 25:
fuel = fuel - 25
laps = laps + 1
print(laps)
C++
int fuel = 100;
int laps = 0;
while (fuel >= 25) {
fuel = fuel - 25;
laps = laps + 1;
}
std::cout << laps << "
";
Two Classic Loop Bugs: Infinite Loops and Off-by-One Errors
1. The Infinite Loop Trap
Look closely at the while (fuel >= 25) loop above. Why does it eventually stop? Because inside the loop body, the statement fuel = fuel - 25 reduces fuel on every pass until fuel reaches 0. If you forgot to include fuel = fuel - 25 inside the loop, fuel would stay 100 forever. The condition 100 >= 25 would remain permanently true, freezing your program in an infinite loop.
while loop must modify at least one variable inside its body that moves the loop condition closer to becoming false.2. Off-by-One Errors (OBOE)
An off-by-one error happens when a loop runs one time too many or one time too few. The most common causes are:
- Confusing
<with<=: In C++,for (int i = 0; i < 5; i++)runs 5 times (for0, 1, 2, 3, 4), whereasfor (int i = 0; i <= 5; i++)runs 6 times (for0, 1, 2, 3, 4, 5). - Python's Exclusive Stop Value: In Python,
range(1, 10)starts at1and stops at9. To include10, you must writerange(1, 11).
Why Do Python and C++ Start Counting at Zero?
New coders often wonder why range(4) and for (int i = 0; i < 4; i++) start at 0 instead of 1. In computer science, zero-based indexing comes from how computer memory works: an index measures the offset (distance) from the beginning of a list or array. The very first item sits right at the start, so its distance from the beginning is 0 steps. Starting your counted loops at 0 and using strictly less than (i < count) has a huge practical benefit: the upper limit number in your loop header always equals the exact number of iterations that will execute!
When to Choose for vs. while
Although any for loop can technically be rewritten as a while loop by creating and incrementing a counter variable manually, experienced developers follow a simple rule of thumb: if you are counting through a fixed range or stepping through a collection of items, always choose a for loop because the counter initialization, stop test, and step update are kept together on a single line, making it much harder to accidentally forget the step update and cause an infinite loop. Save while loops for situations where the stopping point genuinely depends on a changing state—such as waiting for valid user input, simulating fuel depletion, or searching until a target condition is met.
Try It Yourself
Trace the Countdown: Read the loop below and write down the exact numbers printed, in order, and the final value of n after the loop finishes:
n = 16
steps = 0
while n > 1:
n = n // 2
steps = steps + 1
print(n)
Solution Trace:
- Pass 1:
16 > 1is true →nbecomes8,steps = 1, prints8. - Pass 2:
8 > 1is true →nbecomes4,steps = 2, prints4. - Pass 3:
4 > 1is true →nbecomes2,steps = 3, prints2. - Pass 4:
2 > 1is true →nbecomes1,steps = 4, prints1. - Check 5:
1 > 1is false → loop stops after4steps.
CodeCracker