Beginner · Decisions, loops and functions · topic 6 of 42 · 25 min
Loops: for, while, do-while and range-for
Explanation
Why loops?
Printing a multiplication table, adding the marks of 60 students or retrying a password are all "do this again and again" jobs. A loop repeats a block of code. Each repetition is called an iteration.
The for loop
for (int i = 1; i <= 5; ++i) {
std::cout << "7 x " << i << " = " << 7 * i << '\n';
}++i adds 1 to i. In a for loop's update part, ++i and i++ do the same thing; many C++ programmers prefer ++i as a habit because for some types (iterators) it avoids a copy.
while and do-while
int balance = 1000;
int months = 0;
while (balance < 2000) { // checked BEFORE each round
balance = balance * 110 / 100;
++months;
}
std::cout << months << " months\n"; // 8
int pin;
do {
std::cout << "Enter PIN: ";
std::cin >> pin;
} while (pin != 1234); // checked AFTER each round, so it runs at least onceRange-based for
#include <vector>
std::vector<int> marks = {78, 91, 64, 85};
int total = 0;
for (int m : marks) {
total += m;
}
std::cout << "Total: " << total << '\n'; // 318Here std::vector is a list that can grow; you will study it fully in the STL module. For now, think of it as a row of boxes.
break and continue
for (int n = 1; n <= 10; ++n) {
if (n % 2 == 0) continue; // skip even numbers
if (n > 7) break; // stop the whole loop
std::cout << n << ' ';
}
// prints: 1 3 5 7Nested loops
for (int row = 1; row <= 3; ++row) {
for (int col = 1; col <= row; ++col) {
std::cout << '*';
}
std::cout << '\n';
}Common mistakes
- Off-by-one: for (int i = 0; i <= n; ++i) runs n + 1 times. To visit n items indexed 0..n-1, use i < n.
- Infinite loop: forgetting to change the variable in a while loop, so the condition stays true forever. Press Ctrl+C to stop the program.
- Comparing a signed int with v.size() (which is unsigned) gives a warning. Use for (std::size_t i = 0; i < v.size(); ++i) or a range-for.
- A semicolon after the loop header: for (...); { } runs an empty body many times and the block once.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Loops: for, while, do-while and range-for · 1/6
Loops let a program repeat work without copying code. Let us meet the four kinds of loop in C++.
Prefer a video by a teacher? Find free videos on “c++ for while do while range based for loop tutorial” on YouTube ↗
In real life: EMI schedule for a phone
When you buy a phone on EMI, the shop prints a schedule: month 1, month 2 and so on, with the amount left after each payment. A for loop over the months, with a running balance, produces exactly that table.
#include <iostream>
int main() {
int price = 24000, months = 6;
int emi = price / months;
int left = price;
for (int m = 1; m <= months; ++m) {
left -= emi;
std::cout << "Month " << m << ": paid " << emi << ", left " << left << '\n';
}
}Practice (0/4 done)
How many times does this print "Hi"? for (int i = 0; i < 4; ++i) std::cout << "Hi";
What does this print? int s = 0; for (int i = 1; i <= 5; ++i) { if (i == 3) continue; s += i; } std::cout << s;
Which loop is the best choice to keep asking for a PIN until it is right?
Write a program that reads a number n and prints the sum of its digits (for 4521 the answer is 12). Then extend it to print whether n is a palindrome (reads the same backwards, like 1221).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Functions: declare, define, call and returnDecisions, loops and functions · same module
- Overloading, default arguments and recursionDecisions, loops and functions · same module
- Loops and rangesKotlin and Android App Development · Kotlin basics
- Loops: repeating workFrontend Web Development · JavaScript basics
- Loops: for, while, do…while, for…of and for…inJavaScript Programming (language in depth) · Strings, decisions and loops
- Loops: for, while, do-while and foreachC# and .NET · Decisions, loops and methods
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which loop always runs its body at least once?
Answer: do-while
do-while checks its condition after the body.
What does break do inside a loop?
Answer: Exits the loop immediately
break leaves the innermost loop (or switch) at once.
for (int i = 0; i <= 10; i += 2) runs how many times?
Answer: 6
i = 0, 2, 4, 6, 8, 10: six rounds.
Two nested loops each run 1,000 times. How many times does the inner body run?
Answer: 1,000,000
The inner loop runs fully for every outer round: 1,000 × 1,000.
Why does for (int x : v) avoid out-of-range bugs?
Answer: It has no index; it visits exactly the items in the container
A range-for walks from the first to the last element, so there is no index to get wrong.
Which loop always runs its body at least once?Related
Which loop is best to visit every item of an array?Related
Answer: for...of
for...of gives you each item in turn, with no index to manage.
Which loop always runs its body at least once?Related
Answer: do…while
do…while checks the condition after the first run.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks the condition after the body.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Decisions, loops and functions” before its exam: Functions: declare, define, call and return, Overloading, default arguments and recursion.
- Module 2 exam: Decisions, loops and functions · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, References, pointers, arrays and strings. 42 topics left in the course before the final exam.