Menu
Loops in C++

Loops in C++

๐Ÿ”„ 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:

  1. ๐Ÿš€ Initialization: int i = 0 (executes once at start).
  2. โœ… Condition: i < 5 (checked before each iteration; loop continues if true).
  3. ๐Ÿ”„ 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. ๐ŸŽฅ