Loops & Control Flow

⚡ C++ Lesson 6 Beginner

Loops repeat code blocks as long as a condition is satisfied. C++ supports standard loops and range-based loops.

1 Loop Structures: while, do-while, and for

C++ loops match standard layouts:

  • for: Best for iterating over fixed numeric ranges.
  • while: Evaluates conditions before checking execution blocks.
  • do-while: Executes execution blocks first, and then evaluates conditions.
2 Iterations & Loop Control (break/continue)

Let's run a program illustrating loops, continue statements, and break constraints:

C++ — Loops ▶ Run Code
#include <iostream>

int main() {
    std::cout << "For loop sequence: ";
    for (int i = 1; i <= 5; i++) {
        std::cout << i << " ";
    }
    std::cout << "\n";

    // While loop with continue/break
    std::cout << "While sequence (skipping 3, breaking at 6): ";
    int count = 1;
    while (count <= 10) {
        if (count == 3) {
            count++;
            continue; // Skip the rest of this loop iteration
        }
        if (count == 6) {
            break; // Exit the loop entirely
        }
        std::cout << count << " ";
        count++;
    }
    std::cout << "\n";

    return 0;
}
3 Code Challenge
Challenge: Write a loop that calculates the sum of all odd numbers between 1 and 25. Skip the number 13 using the `continue` keyword, and print the computed sum at the end.