Lesson 5 • Beginner

    Loops

    Repeat code efficiently with for, while, and do-while loops — the key to processing data, building patterns, and automating tasks.

    What You'll Learn

    • For loops with custom steps and ranges
    • While and do-while loops
    • Break and continue for loop control
    • Nested loops for patterns and grids

    Why Loops?

    Imagine you need to print "Hello" 1,000 times. Without loops, you'd need 1,000 lines of code. With a loop, you need just 3. Loops let you repeat a block of code as many times as needed.

    C++ gives you three types of loops, each suited for different situations:

    LoopBest ForChecks Condition
    forKnown number of iterationsBefore each iteration
    whileUnknown iterations, condition-basedBefore each iteration
    do-whileMust run at least once (menus, input)After each iteration

    The For Loop

    The for loop has three parts in its header: initialization, condition, and update.

    for (int i = 0; i < 10; i++) {
        // i starts at 0
        // runs while i < 10
        // i increases by 1 each time
        cout << i << " ";  // Prints: 0 1 2 3 4 5 6 7 8 9
    }

    Think of the for loop as saying: "Start at this number, keep going while this condition is true, and take this step each time."

    For Loops

    Count, accumulate, and build multiplication tables

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        // Basic for loop: init; condition; update
        cout << "=== Counting 1 to 10 ===" << endl;
        for (int i = 1; i <= 10; i++) {
            cout << i << " ";
        }
        cout << endl;
        
        // Counting backwards
        cout << "\n=== Countdown ===" << endl;
        for (int i = 5; i >= 1; i--) {
            cout << i << "... ";
        }
        cout << "Liftoff!" << endl;
        
        // Step by 2 — even numbers
        cout << "\n=== Even Numbers (2-20) ===" << endl
    ...

    While & Do-While Loops

    Build a number guessing game and menu system

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        // While loop — check condition FIRST
        cout << "=== While Loop: Powers of 2 ===" << endl;
        int power = 1;
        int count = 0;
        while (power <= 1000) {
            cout << "2^" << count << " = " << power << endl;
            power *= 2;
            count++;
        }
        
        // While loop for validation
        cout << "\n=== Number Guessing ===" << endl;
        int secretNumber = 42;
        int guess = 0;
        int attempts = 0;
        
        // Simulating gues
    ...

    Break & Continue

    Control loop flow and find prime numbers

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        // break — exit the loop immediately
        cout << "=== Break: Find First Multiple of 7 ===" << endl;
        for (int i = 50; i <= 100; i++) {
            if (i % 7 == 0) {
                cout << "First multiple of 7 after 50: " << i << endl;
                break;  // Stop searching
            }
        }
        
        // continue — skip current iteration
        cout << "\n=== Continue: Skip Multiples of 3 ===" << endl;
        for (int i = 1; i <= 15; i++) {
            if 
    ...

    Nested Loops & Patterns

    Create star triangles, number pyramids, and a game board

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        // Nested loops — a loop inside a loop
        
        // Pattern: right triangle
        cout << "=== Star Triangle ===" << endl;
        for (int row = 1; row <= 5; row++) {
            for (int col = 1; col <= row; col++) {
                cout << "* ";
            }
            cout << endl;
        }
        
        // Pattern: number pyramid
        cout << "\n=== Number Pyramid ===" << endl;
        for (int row = 1; row <= 5; row++) {
            // Print spaces for alignment
          
    ...

    Common Mistakes

    ⚠️ Infinite loops: Forgetting to update the loop variable creates an infinite loop. Always ensure the condition will eventually become false.

    ⚠️ Off-by-one errors: Using < vs <= can mean looping one too many or too few times. Double-check boundaries.

    ⚠️ Modifying the loop variable: Changing i inside a for loop body can cause unexpected behavior.

    ⚠️ Wrong loop type: Using while when you know the count (use for), or for when the end is unknown (use while).

    Pro Tips

    💡 Use do-while for menus: Menus should always display at least once — perfect for do-while.

    💡 Accumulator pattern: Initialize a variable before the loop, update inside. Great for sums, products, counting.

    💡 Break early for efficiency: If you're searching for something, use break as soon as you find it.

    💡 Range-based for (C++11): For arrays, use for (int x : arr) to iterate without indices.

    📋 Quick Reference

    ConceptSyntax
    For loopfor (int i=0; i<n; i++) { }
    While loopwhile (condition) { }
    Do-whiledo { } while (condition);
    Breakbreak; — exit loop
    Continuecontinue; — skip iteration
    Range-basedfor (int x : arr) { }

    Lesson Complete!

    You now know how to repeat code with all three loop types, control flow with break/continue, and build patterns with nested loops. Next up: Functions — organize and reuse your code.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service