๐ Loops in C++ (for, while, do-while) - Complete Notes
Video Reference: Loops in C++ by The Cherno | Full Playlist
1. ๐ Introduction to Loops
Timestamp: 00:00:00
- Purpose: Execute code repeatedly without rewriting it.
- Use Cases:
- ๐จ๏ธ Print โHello Worldโ 5 times instead of copy-pasting.
- ๐ฎ Game loops (continuous execution until user quits).
2. ๐ข For Loops
Timestamp: 00:02:00
Syntax:
for (initialization; condition; iteration) {
// Code to repeat
}
Example: Print โHello Worldโ 5 times
for (int i = 0; i < 5; i++) {
std::cout << "Hello World ๐" << std::endl;
}
Breakdown:
- ๐ Initialization:
int i = 0(executes once at start). - โ
Condition:
i < 5(checked before each iteration; loop continues iftrue). - ๐ Iteration:
i++(executes after each iteration).
Key Points:
- ๐๏ธ Flexibility: All three parts (
initialization,condition,iteration) can be modified.int i = 0; for ( ; ; ) { if (i >= 5) break; std::cout << "Hello World ๐" << std::endl; i++; } - โพ๏ธ Endless Loop: Remove condition โ
for (;;) { ... }.
3. ๐ While Loops
Timestamp: 00:07:24
Syntax:
while (condition) {
// Code to repeat
}
Example: Equivalent to the For Loop
int i = 0;
while (i < 5) {
std::cout << "Hello World ๐" << std::endl;
i++;
}
Use Case:
- ๐ฎ Game Loop:
bool isRunning = true; while (isRunning) { UpdateGame(); RenderGraphics(); }
4. โฐ Do-While Loops
Timestamp: 00:10:12
Syntax:
do {
// Code to execute at least once
} while (condition);
Example:
int i = 0;
do {
std::cout << "Hello World ๐" << std::endl;
i++;
} while (i < 5);
Key Difference:
- Executes the body at least once, even if the condition is initially
false.
5. ๐ Key Differences
| Loop Type | When to Use | Notes |
|โโโโโ-|โโโโโโโโโโโโโ|โโโโโโโโโโโโ-|
| ๐ข For | Known number of iterations | Compact syntax for index-based loops |
| ๐ While | Condition-based repetition | Flexible for dynamic conditions |
| โฐ Do-While| Execute code once before checking | Rarely used; specific edge cases |
6. ๐ Summary
- For Loops: Best for fixed iterations (e.g., arrays, counting).
- While Loops: Ideal for unknown iterations (e.g., game loops).
- โ ๏ธ Avoid Infinite Loops: Ensure the loop condition eventually becomes
false.
Next Steps: Use loops with arrays (covered in future videos).
Need More Context? Jump to the full video for visual explanations. ๐ฅ
