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

TEXT 📖 Display only
for (initialization; condition; update) {
 // Loop body: repeats while condition is true
}

Execution flow:

  1. Initialization: Executed only once (typically used to declare the loop variable)
  2. Check condition: If true, execute the loop body; if false, exit the loop
  3. Execute loop body
  4. Update: After the loop body executes, update the loop variable
  5. Go back to step 2

▶ Example 1: Output 1-10 (Difficulty ⭐)

CPP
#include <iostream>

int main() {
 for (int i = 1; i <= 10; i++) {
 std::cout << i << " ";
 }
 std::cout << std::endl;
 
 return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
1
2
3
4
5
6
7
8
9

Code breakdown:

  1. int i = 1: Initialization, i starts at 1
  2. i <= 10: Condition, loop continues as long as i <= 10
  3. std::cout << i << " ": Loop body, output i
  4. i++: Update, increment i by 1


2. The while Loop

(1) 2.1 Basic Syntax

TEXT 📖 Display only
while (condition) {
 // Loop body: repeats while condition is true
}

Execution flow:

  1. Check the condition
  2. If true, execute the loop body
  3. 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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
1 2 3 4 5 6 7 8 9 10 


3. The do-while Loop

(1) 3.1 Basic Syntax

TEXT 📖 Display only
do {
 // Loop body
} while (condition);

Execution flow:

  1. Execute the loop body (at least once)
  2. Check the condition
  3. If true, go back to step 1

💡 Key point: The do-while loop executes at least once!

▶ Example 3: Number Guessing Game (Difficulty ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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:



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 ⭐)

CPP
#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 ⭐)

CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
1 x 1 = 1	
1 x 2 = 2	2 x 2 = 4	
...

💡 Execution flow:



7. Infinite Loops

If the loop condition is always true, an infinite loop is formed.

▶ Example 5: Infinite Loop (Difficulty ⭐)

CPP
#include <iostream>

int main() {
 while (true) { // Condition is always true
 std::cout << "Infinite loop..." << std::endl;
 }
 
 return 0; // This line is never reached
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter a positive integer: 5
5 ! is: 120

Run result:

TEXT 📖 Display only
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

Q Can the semicolons in a for loop be omitted?
A You can omit parts but not the semicolons. for (; i <= 10; i++) omits initialization, for (;;) is an infinite loop (equivalent to while(true)).
Q Can while and for be converted to each other?
A Yes. Any 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.
Q How do break and continue work in nested loops?
A break only exits the current level of loop. To exit multiple levels, use a "flag variable" or goto (not recommended as an alternative).

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Use a for loop to output all numbers from 1-100 that are divisible by 3.

  2. Intermediate (Difficulty ⭐⭐): Use nested loops to print the following pattern:

TEXT 📖 Display only
*
**
***
****
*****
  1. Challenge (Difficulty ⭐⭐⭐): Write a program that lets the user enter a positive integer n, then outputs n rows of Pascal's Triangle.
TEXT 📖 Display only
Please enter number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

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!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏