Loops
beginnerWhat you'll learn
- Explain why a loop replaces repeated statements.
- Write a for, while, or do-while loop that terminates correctly.
- Trace a loop and predict its output before running it.
Loops repeat a block of code multiple times. They are one of the most fundamental control structures in programming.
Problem
You must print the numbers 1 to 10. Writing them by hand looks like this:
Goal: Print 1 through 10 with a single repeating statement instead of ten separate lines.
Ten near-identical lines is slow and easy to get wrong. Look for the pattern:
START
set i = 1
WHILE i <= 10
print i
i = i + 1
ENDC++ expresses 'repeat' with a loop:
Now that the reason is clear, the rest of this note explains the syntax and the three loop types.
Why Loops Matter
- Avoid repeating the same code for similar tasks
- Process collections of data (arrays, strings, files)
- Implement algorithms (searching, sorting, aggregation)
- Create repetitive behaviors (animations, polling, retries)
Three Types of Loops
- for loop: when you know the number of iterations
- while loop: when you don't know iterations, check before each
- do-while loop: execute at least once, then check
for Loop
while Loop
do-while Loop
Infinite Loops
Complete Program: Three Ways to Count to 5
Common mistakes: forgetting the update step so a while loop never terminates, an off-by-one bound (i <= n vs i < n) that runs one iteration too many, and dropping the semicolon after do-while(...).
Key takeaway: Choose the right loop type — for when you know the count, while for unknown iterations, and do-while when you need at least one execution.
Try it: Write a program that uses each of the three loop types (for, while, do-while) to print numbers 1 through 5.