Loops (for, while, do-while, Range-Based for)
Loops allow you to repeat a block of code multiple times without duplicating lines. Each repetition of a loop is called an iteration.
1. The while Loop
Repeats a block of code as long as a condition remains true. Because the condition is checked before the loop body runs, a while loop might execute 0 times if the condition starts out false. Ideal when you don't know in advance how many iterations you need (e.g., waiting for valid user input).
2. The do-while Loop
Similar to while, except the condition is checked after the loop body executes. This guarantees the code inside runs at least once, even if the condition is initially false. Notice the mandatory semicolon ; after the while(condition);.
3. The Standard for Loop
Best when you know the exact number of iterations needed. It packs three components into its header separated by semicolons:
for (initialization; condition; update)
1. Initialization: Runs once before the loop starts (e.g., int i = 0).
2. Condition: Checked before every iteration; loop stops when false (e.g., i < 5).
3. Update: Runs at the end of each iteration (e.g., i++).
4. Range-Based for Loop (Modern C++)
Introduced in C++11 to cleanly iterate over every item in a collection (like an array, string, or vector) without managing index counters:
for (type item : collection)
#include <iostream> #include <string> int main() { // 1. Standard for loop (prints 1 to 5) for (int i = 1; i <= 5; i++) { std::cout << i << " "; } std::cout << "\n"; // 2. while loop int countdown = 3; while (countdown > 0) { std::cout << "T-minus " << countdown << "\n"; countdown--; } // 3. do-while loop (runs at least once) int number = 10; do { std::cout << "Runs once even though number is 10\n"; } while (number < 5); // 4. Range-based for loop std::string word = "CODE"; for (char letter : word) { std::cout << letter << "-"; } std::cout << "\n"; return 0; }
Watch companion video on YouTube
Sign in to save your progress