Loops
By the end of this lesson you'll be able to repeat code with for , while , and do-while loops, walk through a whole collection with a range-based for , and steer any loop with break and continue — the engine behind processing data, building patterns, and automating work.
Part of the free C++ course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
A loop is a washing machine cycle . You set it up once (init), it keeps spinning while a condition holds (the timer hasn't finished), and each rotation does the same job (the body) before stepping forward (update). A for loop is a timed cycle — you know it'll run, say, 30 minutes. A while loop is "keep rinsing while the water's still soapy" — you stop when a condition changes, not after a fixed count. A do-while always does at least one spin before it checks whether to stop. Same drum, different rules for when to stop.
📊 Which Loop, When?
Loop
Best for
Checks condition
for
A known number of repeats (counting)
Before each pass
while
Repeat until a condition changes
do-while
Must run at least once (menus, prompts)
After each pass
range-for
Visit every item in a collection
Per element, automatically
1. The for Loop
The for loop packs three things into its header: initialization (set up a counter), a condition (keep going while this is true), and an update (change the counter each pass). Read it as: "start here, keep going while this holds, take this step each time." It's the loop you reach for when you know how many times to repeat. Read this worked example, run it, then you'll write your own.
Your turn. The program below is almost complete — fill in the two blanks marked ___ using the hints, then run it.
2. while and do-while
Use while when you don't know the count up front — you loop until something changes. It checks the condition before the body, so it can run zero times. do-while flips that: it runs the body once first , then checks the condition, so it always runs at least once. The one rule both share: something inside the body must move you toward the condition becoming false, or you'll loop forever.
3. The Range-Based for
When you just want to visit every item in a collection, the range-based for is cleaner and safer than a counter — there's no index to get wrong. The shape is for (auto x : vec) , read as "for each x in vec ." Plain auto x makes a copy of each element (fine for small types like int ). For bigger items like strings, use const auto& x — the & means "look at the real element, don't copy it," and const promises you won't change it.
Now you try. Walk the prices vector with a range-based for and add up the total. Fill in the two blanks:
4. break , continue & Nested Loops
break exits a loop immediately — great for stopping as soon as you've found what you wanted. continue skips just the rest of the current pass and jumps to the next one — great for ignoring items you don't care about. And a loop can live inside another loop: the inner loop runs all the way through for every single pass of the outer one, which is how you build grids and patterns.
Pro Tips
- 💡 Prefer the range-based for when you don't need the index — there's no < vs <= boundary to get wrong.
- 💡 Use const auto& for anything bigger than an int (strings, vectors, objects) to skip a needless copy each pass.
- 💡 Accumulator pattern: start a variable before the loop, update it inside. The bedrock of sums, products, and counts.
- 💡 Break early to save work: once a search finds its answer, break out instead of finishing the loop.
Common Errors (and the fix)
- Off-by-one ( < vs <= ): for (int i = 0; i <= 5; i++) runs 6 times (0–5), not 5. If you want 5 passes use i < 5 . Decide whether the last value is included, then match the operator.
- Infinite loop (missing update): a while (x < 10) with no x++ (or x *= 2 ) inside never ends — the condition can never become false. Make sure the body changes the value being tested.
- Wrong boundary direction: counting down with for (int i = 5; i > = 1; i--) needs -- and > = . Pairing i-- with i <= 5 spins forever.
- Copying in a range-for when you meant to reference: for (auto x : bigStrings) copies every element. For large types use for (const auto& x : bigStrings) — and if you actually want to modify the elements, drop the const and keep the & .
- Declaring the counter outside its scope: a variable declared with int i inside for (int i...) only lives in the loop. Referencing i after the loop gives "'i' was not declared in this scope" .
📋 Quick Reference
Goal
Use
Shape
Count a known number of times
for (int i=0; i<n; i++) { }
Repeat until a condition flips
while (cond) { }
Run at least once (menus)
do { } while (cond);
Visit every item (small type)
for (auto x : vec) { }
Visit every item (no copy)
for (const auto& x : vec) { }
Leave the loop now
break
break;
Skip to the next pass
continue
continue;
Frequently Asked Questions
Mini-Challenge: Count the Passing Scores
No blanks this time — just a brief and an outline to keep you on track. Build it, run it, and check your output against the example in the comments. This is exactly the kind of small loop real programs are full of.
🎉 Lesson Complete
- ✅ for packs init, condition, and update into one header — use it for a known count
- ✅ while checks first (may run zero times); do-while runs once then checks
- ✅ for (auto x : vec) visits every item; const auto& avoids copies
- ✅ break exits the loop; continue skips to the next pass
- ✅ Nested loops run the inner loop fully for every outer pass — patterns and grids
- ✅ Watch < vs <= for off-by-one, and always update the variable you test
- ✅ Next lesson: Functions — organize and reuse your code
Practice quiz
What are the three parts of a for loop header, in order?
- condition; init; update
- update; init; condition
- init; condition; update
- init; update; condition
Answer: init; condition; update. A for loop is for (init; condition; update).
Which loop checks its condition AFTER running the body, so it always runs at least once?
- do-while
- for
- while
- range-for
Answer: do-while. do-while runs the body first, then checks the condition.
How many times does 'for (int i = 0; i <= 5; i++)' run?
- 5
- 4
- Infinite
- 6
Answer: 6. i takes values 0,1,2,3,4,5 — that is 6 iterations because of <=.
What does 'break' do inside a loop?
- Skips to the next iteration
- Exits the loop immediately
- Restarts the loop
- Pauses for one second
Answer: Exits the loop immediately. break exits the entire loop immediately and continues after it.
What does 'continue' do inside a loop?
- Skips the rest of the current iteration and goes to the next
- Exits the loop
- Ends the program
- Repeats the current iteration
Answer: Skips the rest of the current iteration and goes to the next. continue skips the rest of this pass and jumps to the next iteration.
What is the shape of a range-based for loop over a vector v?
- for (x in v)
- foreach (v as x)
- for (auto x : v)
- for x : v ()
Answer: for (auto x : v). A range-based for is for (auto x : v), read as 'for each x in v'.
Why use 'const auto&' instead of 'auto' in a range-based for over strings?
- It is required syntax
- It avoids copying each element
- It modifies the elements
- It runs the loop backwards
Answer: It avoids copying each element. const auto& references the real element so no copy is made, and const promises not to change it.
What is the most common cause of an infinite loop?
- Using a for loop
- Using break
- Having too many iterations
- Forgetting the update step so the condition never becomes false
Answer: Forgetting the update step so the condition never becomes false. If nothing inside the body moves toward the condition being false, the loop runs forever.
After 'int sum = 0; for (int i = 1; i <= 100; i++) sum += i;', what is sum?
- 100
- 5050
- 5000
- 10100
Answer: 5050. The accumulator adds 1 through 100, which totals 5050.
In nested loops, how often does the inner loop run relative to the outer?
- Once total
- Only on the first outer pass
- Fully, for every single pass of the outer loop
- Half as often
Answer: Fully, for every single pass of the outer loop. The inner loop runs all the way through for every iteration of the outer loop.
Continue this course
- Previous: Control Flow
- Next: Functions