C++: Loop Structures
Last updated: 2026-08-26
Suppose you need to print "Hello" 100 times on the screen. How would you do it?
Copy and paste 100 lines of
std::cout << "Hello" << std::endl;? That's ridiculous.A programmer's approach — loops. Let the computer repeat a block of code until a condition is met.
1. The for Loop
(1) 1.1 Basic Syntax
for (initialization; condition; update) {
// Loop body: repeats while condition is true
}
Execution flow:
- Initialization: Executed only once (typically used to declare the loop variable)
- Check condition: If true, execute the loop body; if false, exit the loop
- Execute loop body
- Update: After the loop body executes, update the loop variable
- Go back to step 2
▶ Example 1: Output 1-10 (Difficulty ⭐)
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
Code breakdown:
int i = 1: Initialization, i starts at 1i <= 10: Condition, loop continues as long as i <= 10std::cout << i << " ": Loop body, output ii++: Update, increment i by 1
2. The while Loop
(1) 2.1 Basic Syntax
while (condition) {
// Loop body: repeats while condition is true
}
Execution flow:
- Check the condition
- If true, execute the loop body
- Go back to step 1
💡 Key point: The while loop updates the loop variable inside the loop body!
▶ Example 2: Output 1-10 with while (Difficulty ⭐)
#include <iostream>
int main() {
int i = 1; // Initialization
while (i <= 10) { // Condition
std::cout << i << " ";
i++; // Update (inside the loop body!)
}
std::cout << std::endl;
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
3. The do-while Loop
(1) 3.1 Basic Syntax
do {
// Loop body
} while (condition);
Execution flow:
- Execute the loop body (at least once)
- Check the condition
- If true, go back to step 1
💡 Key point: The do-while loop executes at least once!
▶ Example 3: Number Guessing Game (Difficulty ⭐⭐)
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
int secretNumber = std::rand() % 100 + 1;
int guess;
do {
std::cout << "Guess a number from 1-100: ";
std::cin >> guess;
if (guess > secretNumber) {
std::cout << "Too high!" << std::endl;
} else if (guess < secretNumber) {
std::cout << "Too low!" << std::endl;
}
} while (guess != secretNumber);
std::cout << "🎉 Got it!The answer is " << secretNumber << std::endl;
return 0;
}
Output:
Guess a number from 1-100:
Too high!
Too low!
🎉 Got it!The answer is 42
💡 Why use do-while? Because the user must guess at least once, so the loop body must execute at least once.
4. for vs while vs do-while
| Loop Type | Best Use Case | Characteristic |
|---|---|---|
| for | Known number of iterations | Initialization, condition, and update are grouped together — clear structure |
| while | Unknown iterations but known condition | Loop variable is updated inside the loop body |
| do-while | Must execute at least once | Loop body executes at least once |
Selection advice:
- If you know the number of iterations (e.g., "output 100 times"), use for
- If you don't know the number of iterations but know the condition (e.g., "keep guessing until correct"), use while or do-while
5. break and continue
(1) 5.1 break: Exit the Entire Loop
break is used to end a loop early.
Example: Find the first number divisible by 7 (Difficulty ⭐)
#include <iostream>
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
std::cout << "The first number divisible by 7 is: " << i << std::endl;
break; // Exit the loop after finding it
}
}
return 0;
}
(2) 5.2 continue: Skip Current Iteration
continue is used to skip the current iteration and go directly to the next one.
Example: Output odd numbers from 1-10 (Difficulty ⭐)
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // If even, skip this iteration
}
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
6. Nested Loops
A loop can contain another loop inside it — this is called a nested loop.
▶ Example 4: Print Multiplication Table (Difficulty ⭐⭐)
#include <iostream>
int main() {
for (int i = 1; i <= 9; i++) { // Outer loop: controls rows
for (int j = 1; j <= i; j++) { // Inner loop: controls columns
std::cout << j << " x " << i << " = " << i * j << "\t";
}
std::cout << std::endl; // Newline
}
return 0;
}
Output:
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
...
💡 Execution flow:
- Outer loop
i = 1: Inner loopjgoes from 1 to 1, outputs 1 column - Outer loop
i = 2: Inner loopjgoes from 1 to 2, outputs 2 columns - ...
- Outer loop
i = 9: Inner loopjgoes from 1 to 9, outputs 9 columns
7. Infinite Loops
If the loop condition is always true, an infinite loop is formed.
▶ Example 5: Infinite Loop (Difficulty ⭐)
#include <iostream>
int main() {
while (true) { // Condition is always true
std::cout << "Infinite loop..." << std::endl;
}
return 0; // This line is never reached
}
Output:
Infinite loop...
💡 How to stop? Press Ctrl + C to forcefully terminate the program.
💡 Are infinite loops useful? Yes! For example, server programs need to keep running and wait for user requests.
8. Practice: Calculating Factorials
▶ Example 6: Calculate n! (Difficulty ⭐⭐)
#include <iostream>
int main() {
int n;
std::cout << "Please enter a positive integer: ";
std::cin >> n;
long long factorial = 1; // Use long long to prevent overflow
for (int i = 1; i <= n; i++) {
factorial *= i;
}
std::cout << n << " ! is: " << factorial << std::endl;
return 0;
}
Output:
Please enter a positive integer: 5
5 ! is: 120
Run result:
Please enter a positive integer: 5
5 ! is: 120
💡 Tip: 20! exceeds the range of long long, so even with long long you can only calculate up to 20.
❓ FAQ
for (; i <= 10; i++) omits initialization, for (;;) is an infinite loop (equivalent to while(true)).for loop can be rewritten as while, and vice versa. Selection rule: use for when you know the count, use while when you know the condition.break only exits the current level of loop. To exit multiple levels, use a "flag variable" or goto (not recommended as an alternative).📖 Summary
- for loop: Use when you know the number of iterations
- while loop: Use when you don't know the number of iterations but know the condition
- do-while loop: Use when the loop must execute at least once
- break: Exit the entire loop
- continue: Skip the current iteration and move to the next
- Loops can be nested; the inner loop runs completely for each iteration of the outer loop
📝 Exercises
-
Basic (Difficulty ⭐): Use a for loop to output all numbers from 1-100 that are divisible by 3.
-
Intermediate (Difficulty ⭐⭐): Use nested loops to print the following pattern:
*
**
***
****
*****
- Challenge (Difficulty ⭐⭐⭐): Write a program that lets the user enter a positive integer n, then outputs n rows of Pascal's Triangle.
Please enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
- for loop: use when you know the iteration count
- while loop: use when you know the condition
- do-while loop: use when it must execute at least once
- break exits the loop, continue skips the current iteration
- In nested loops, the inner loop runs completely for each outer loop iteration
13. 🚀 Next Step
Now that you've learned loops, next we'll learn functions (Lesson 08) — packaging code into reusable modules to make programs cleaner and easier to maintain!