Module 2.3

Loops in C++

Master iteration in C++ with for, while, and do-while loops. Learn range-based for loops, loop control statements, and nested loops to write efficient repetitive code.

40 min read
Beginner
Hands-on Examples
What You'll Learn
  • for loops
  • while and do-while loops
  • Range-based for loops
  • break and continue
  • Nested loops
Contents
01

Introduction to Loops

Loops allow you to execute a block of code repeatedly. Instead of writing the same code multiple times, you can use loops to automate repetitive tasks efficiently. C++ provides several loop constructs for different scenarios.

Concept

Loop

A loop is a control structure that repeats a block of code as long as a specified condition remains true. Each execution of the loop body is called an iteration.

Key Components: Initialization, Condition, Update, Body

Types of Loops in C++

for

Best when you know the number of iterations

while

Check condition before each iteration

do-while

Execute at least once, then check

range-based

Iterate over containers (C++11)

02

The for Loop

The for loop is the most commonly used loop when you know in advance how many times you want to iterate. It combines initialization, condition, and update in a single line.

Basic Syntax

#include <iostream>
using namespace std;

int main() {
    // for (initialization; condition; update) { body }
    
    // Print numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;  // Output: 1 2 3 4 5
    
    // Execution flow:
    // 1. Initialize i = 1
    // 2. Check condition: i <= 5 (true)
    // 3. Execute body: print 1
    // 4. Update: i++ (i becomes 2)
    // 5. Repeat steps 2-4 until condition is false
    
    return 0;
}

for Loop Variations

#include <iostream>
using namespace std;

int main() {
    // Counting down
    cout << "Countdown: ";
    for (int i = 5; i >= 1; i--) {
        cout << i << " ";
    }
    cout << endl;  // Output: 5 4 3 2 1
    
    // Step by 2
    cout << "Even numbers: ";
    for (int i = 0; i <= 10; i += 2) {
        cout << i << " ";
    }
    cout << endl;  // Output: 0 2 4 6 8 10
    
    // Multiple variables
    cout << "Two variables: ";
    for (int i = 0, j = 10; i < j; i++, j--) {
        cout << "(" << i << "," << j << ") ";
    }
    cout << endl;  // Output: (0,10) (1,9) (2,8) (3,7) (4,6)
    
    // Omitting parts (all three are optional)
    int k = 0;
    for ( ; k < 3; ) {
        cout << k << " ";
        k++;
    }
    cout << endl;  // Output: 0 1 2
    
    return 0;
}

Practical Example: Sum and Factorial

#include <iostream>
using namespace std;

int main() {
    // Calculate sum of 1 to n
    int n = 10;
    int sum = 0;
    
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    cout << "Sum of 1 to " << n << ": " << sum << endl;  // 55
    
    // Calculate factorial
    int num = 5;
    long long factorial = 1;
    
    for (int i = 1; i <= num; i++) {
        factorial *= i;
    }
    cout << num << "! = " << factorial << endl;  // 120
    
    // Print multiplication table
    int table = 7;
    cout << "\nMultiplication table of " << table << ":" << endl;
    for (int i = 1; i <= 10; i++) {
        cout << table << " x " << i << " = " << (table * i) << endl;
    }
    
    return 0;
}
03

The while Loop

The while loop checks the condition before each iteration. It's ideal when you don't know in advance how many times you need to loop.

#include <iostream>
using namespace std;

int main() {
    // Basic while loop
    int count = 1;
    
    while (count <= 5) {
        cout << count << " ";
        count++;
    }
    cout << endl;  // Output: 1 2 3 4 5
    
    // If condition is false initially, body never executes
    int x = 10;
    while (x < 5) {
        cout << "This won't print" << endl;
        x++;
    }
    
    return 0;
}

Practical Examples

#include <iostream>
using namespace std;

int main() {
    // Sum digits of a number
    int number = 12345;
    int digitSum = 0;
    int temp = number;
    
    while (temp > 0) {
        digitSum += temp % 10;  // Get last digit
        temp /= 10;             // Remove last digit
    }
    cout << "Sum of digits of " << number << ": " << digitSum << endl;  // 15
    
    // Reverse a number
    int num = 1234;
    int reversed = 0;
    temp = num;
    
    while (temp > 0) {
        int digit = temp % 10;
        reversed = reversed * 10 + digit;
        temp /= 10;
    }
    cout << "Reverse of " << num << ": " << reversed << endl;  // 4321
    
    // Count digits
    int value = 987654;
    int digitCount = 0;
    temp = value;
    
    while (temp > 0) {
        digitCount++;
        temp /= 10;
    }
    cout << value << " has " << digitCount << " digits" << endl;  // 6
    
    return 0;
}

User Input with while

#include <iostream>
using namespace std;

int main() {
    int input;
    int sum = 0;
    
    cout << "Enter numbers (0 to stop):" << endl;
    
    cin >> input;
    while (input != 0) {
        sum += input;
        cin >> input;
    }
    
    cout << "Total sum: " << sum << endl;
    
    // Validation loop
    int age;
    cout << "Enter your age (1-120): ";
    cin >> age;
    
    while (age < 1 || age > 120) {
        cout << "Invalid! Enter age (1-120): ";
        cin >> age;
    }
    
    cout << "Valid age: " << age << endl;
    
    return 0;
}
04

The do-while Loop

The do-while loop executes the body first, then checks the condition. This guarantees at least one execution, making it perfect for menus and input validation.

#include <iostream>
using namespace std;

int main() {
    // Basic do-while
    int count = 1;
    
    do {
        cout << count << " ";
        count++;
    } while (count <= 5);
    
    cout << endl;  // Output: 1 2 3 4 5
    
    // Executes at least once even if condition is false
    int x = 10;
    do {
        cout << "This prints once!" << endl;
        x++;
    } while (x < 5);  // Condition false, but body ran once
    
    return 0;
}

Menu System Example

#include <iostream>
using namespace std;

int main() {
    int choice;
    
    do {
        cout << "\n===== MENU =====" << endl;
        cout << "1. Say Hello" << endl;
        cout << "2. Say Goodbye" << endl;
        cout << "3. Show Time" << endl;
        cout << "0. Exit" << endl;
        cout << "Choice: ";
        cin >> choice;
        
        switch (choice) {
            case 1:
                cout << "Hello, World!" << endl;
                break;
            case 2:
                cout << "Goodbye, World!" << endl;
                break;
            case 3:
                cout << "It's coding time!" << endl;
                break;
            case 0:
                cout << "Exiting..." << endl;
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
    } while (choice != 0);
    
    return 0;
}

Input Validation with do-while

#include <iostream>
using namespace std;

int main() {
    int password;
    const int CORRECT_PIN = 1234;
    int attempts = 0;
    const int MAX_ATTEMPTS = 3;
    
    do {
        cout << "Enter PIN: ";
        cin >> password;
        attempts++;
        
        if (password != CORRECT_PIN) {
            cout << "Wrong PIN! " << (MAX_ATTEMPTS - attempts) 
                 << " attempts remaining." << endl;
        }
    } while (password != CORRECT_PIN && attempts < MAX_ATTEMPTS);
    
    if (password == CORRECT_PIN) {
        cout << "Access granted!" << endl;
    } else {
        cout << "Account locked!" << endl;
    }
    
    return 0;
}

Loop Comparison

Aspect for while do-while
Condition Check Before iteration Before iteration After iteration
Minimum Executions 0 0 1
Best Use Case Known iteration count Unknown iterations At least one execution
Init/Update Location In loop header Separate from loop Separate from loop
05

Range-Based for Loop (C++11)

The range-based for loop provides a cleaner syntax for iterating over containers like arrays, vectors, and strings. Introduced in C++11, it's the preferred way to iterate when you don't need the index.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    // Array iteration
    int numbers[] = {10, 20, 30, 40, 50};
    
    cout << "Array elements: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;  // Output: 10 20 30 40 50
    
    // Vector iteration
    vector<string> fruits = {"Apple", "Banana", "Cherry"};
    
    cout << "Fruits: ";
    for (string fruit : fruits) {
        cout << fruit << " ";
    }
    cout << endl;  // Output: Apple Banana Cherry
    
    // String iteration (character by character)
    string text = "Hello";
    
    cout << "Characters: ";
    for (char c : text) {
        cout << c << "-";
    }
    cout << endl;  // Output: H-e-l-l-o-
    
    return 0;
}

By Value vs By Reference

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};
    
    // By value (copy) - cannot modify original
    cout << "By value (doubled locally): ";
    for (int n : nums) {
        n *= 2;  // Only modifies the copy
        cout << n << " ";
    }
    cout << endl;  // Output: 2 4 6 8 10
    
    // Original unchanged
    cout << "Original: ";
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;  // Output: 1 2 3 4 5
    
    // By reference - modifies original
    for (int& n : nums) {
        n *= 2;  // Modifies original
    }
    
    cout << "After reference modification: ";
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;  // Output: 2 4 6 8 10
    
    // By const reference - efficient for large objects, read-only
    vector<string> names = {"Alice", "Bob", "Charlie"};
    
    for (const string& name : names) {
        cout << name << " ";
        // name = "Changed";  // Error! Can't modify const reference
    }
    cout << endl;
    
    return 0;
}

Using auto Keyword

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};
    
    // auto deduces the type automatically
    cout << "With auto: ";
    for (auto num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // auto with reference
    for (auto& num : numbers) {
        num += 10;
    }
    
    // auto with const reference (recommended for read-only)
    cout << "Modified: ";
    for (const auto& num : numbers) {
        cout << num << " ";
    }
    cout << endl;  // Output: 11 12 13 14 15
    
    // Useful with complex types like maps
    map<string, int> ages = {{"Alice", 25}, {"Bob", 30}};
    
    for (const auto& pair : ages) {
        cout << pair.first << ": " << pair.second << endl;
    }
    
    return 0;
}
06

Loop Control Statements

Loop control statements (break, continue, goto) allow you to alter the normal flow of loop execution.

break Statement

#include <iostream>
using namespace std;

int main() {
    // break exits the loop immediately
    cout << "Finding first multiple of 7: ";
    for (int i = 1; i <= 100; i++) {
        if (i % 7 == 0) {
            cout << i << endl;  // 7
            break;  // Exit loop
        }
    }
    
    // Search in array
    int arr[] = {10, 25, 30, 45, 50};
    int target = 30;
    bool found = false;
    
    for (int i = 0; i < 5; i++) {
        if (arr[i] == target) {
            cout << "Found " << target << " at index " << i << endl;
            found = true;
            break;
        }
    }
    
    if (!found) {
        cout << target << " not found" << endl;
    }
    
    return 0;
}

continue Statement

#include <iostream>
using namespace std;

int main() {
    // continue skips the rest of current iteration
    cout << "Odd numbers 1-10: ";
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        cout << i << " ";
    }
    cout << endl;  // Output: 1 3 5 7 9
    
    // Skip specific values
    cout << "Numbers except 5: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue;
        }
        cout << i << " ";
    }
    cout << endl;  // Output: 1 2 3 4 6 7 8 9 10
    
    // Process only positive numbers
    int nums[] = {3, -1, 4, -2, 5, -3};
    int sum = 0;
    
    for (int num : nums) {
        if (num < 0) {
            continue;  // Skip negative numbers
        }
        sum += num;
    }
    cout << "Sum of positives: " << sum << endl;  // 12
    
    return 0;
}

break vs continue

#include <iostream>
using namespace std;

int main() {
    cout << "Using break at 5: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 5) break;
        cout << i << " ";
    }
    cout << endl;  // Output: 1 2 3 4
    
    cout << "Using continue at 5: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 5) continue;
        cout << i << " ";
    }
    cout << endl;  // Output: 1 2 3 4 6 7 8 9 10
    
    return 0;
}
Note: In nested loops, break and continue only affect the innermost loop. To break out of multiple loops, consider using a flag variable or restructuring with functions.
07

Nested Loops

Nested loops are loops inside other loops. The inner loop completes all its iterations for each iteration of the outer loop. They're essential for working with multi-dimensional data and patterns.

#include <iostream>
using namespace std;

int main() {
    // Basic nested loop
    cout << "Nested loop output:" << endl;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << "(" << i << "," << j << ") ";
        }
        cout << endl;
    }
    // Output:
    // (1,1) (1,2) (1,3)
    // (2,1) (2,2) (2,3)
    // (3,1) (3,2) (3,3)
    
    return 0;
}

Pattern Printing

#include <iostream>
using namespace std;

int main() {
    int n = 5;
    
    // Right triangle
    cout << "Right Triangle:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    /*
    *
    * *
    * * *
    * * * *
    * * * * *
    */
    
    // Number pyramid
    cout << "\nNumber Pyramid:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }
    /*
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    */
    
    // Inverted triangle
    cout << "\nInverted Triangle:" << endl;
    for (int i = n; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    
    return 0;
}

2D Array Traversal

#include <iostream>
using namespace std;

int main() {
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    // Print matrix
    cout << "Matrix:" << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    
    // Find sum of all elements
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            sum += matrix[i][j];
        }
    }
    cout << "Sum of all elements: " << sum << endl;  // 78
    
    // Find maximum element
    int maxVal = matrix[0][0];
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (matrix[i][j] > maxVal) {
                maxVal = matrix[i][j];
            }
        }
    }
    cout << "Maximum element: " << maxVal << endl;  // 12
    
    return 0;
}

Breaking from Nested Loops

#include <iostream>
using namespace std;

int main() {
    // Using a flag to break from nested loops
    bool found = false;
    int target = 7;
    
    for (int i = 1; i <= 5 && !found; i++) {
        for (int j = 1; j <= 5 && !found; j++) {
            cout << "Checking (" << i << "," << j << ")" << endl;
            if (i * j == target) {
                cout << "Found! " << i << " * " << j << " = " << target << endl;
                found = true;
            }
        }
    }
    
    return 0;
}
08

Infinite Loops

An infinite loop runs forever unless explicitly broken. While usually a bug, infinite loops are sometimes intentional for continuous processes like servers or game loops.

#include <iostream>
using namespace std;

int main() {
    // Intentional infinite loops
    
    // Method 1: while(true)
    // while (true) {
    //     // Game loop, server, etc.
    // }
    
    // Method 2: for(;;)
    // for (;;) {
    //     // Runs forever
    // }
    
    // Method 3: while(1)
    // while (1) {
    //     // Runs forever
    // }
    
    // Practical example: Event loop with exit condition
    int input;
    while (true) {
        cout << "Enter a number (negative to quit): ";
        cin >> input;
        
        if (input < 0) {
            cout << "Goodbye!" << endl;
            break;  // Exit the infinite loop
        }
        
        cout << "Square: " << (input * input) << endl;
    }
    
    return 0;
}
Avoiding Accidental Infinite Loops:
  • Always ensure the loop condition can become false
  • Make sure to update loop variables inside the loop
  • Be careful with floating-point comparisons
  • Use Ctrl+C to stop a runaway program

Common Infinite Loop Bugs

// Bug 1: Forgetting to update counter
int i = 0;
while (i < 5) {
    cout << i;
    // i++ missing! Loop never ends
}

// Bug 2: Wrong comparison
for (int i = 0; i != 10; i += 3) {
    cout << i;
    // i goes 0, 3, 6, 9, 12, 15... never equals 10!
}

// Bug 3: Modifying loop variable incorrectly
for (int i = 10; i >= 0; i++) {  // Should be i--
    cout << i;
}

Key Takeaways

for Loop

Best for known iteration counts

while Loop

Check condition first, may not execute

do-while Loop

Executes at least once

Range-Based for

Clean syntax for containers (C++11)

break & continue

Control loop flow; exit or skip

Nested Loops

Inner loop completes for each outer

Knowledge Check

Quick Quiz

Test what you have learned about C++ loops

1 How many times will this loop execute?
for (int i = 0; i < 5; i++) {
    cout << i;
}
2 Which loop guarantees at least one execution?
3 What does the continue statement do?
4 What is the output?
for (int i = 1; i <= 3; i++) {
    if (i == 2) break;
    cout << i;
}
5 How do you modify elements in a range-based for loop?
6 In nested loops, what does break affect?
Answer all questions to check your score