Skillversitas

Loops in C++

Looping is one of the fundamental features in programming that allows a block of code to be executed repeatedly. C++ provides four main types of loops: for, while, do-while, and range-based for (C++11). Each type has different characteristics and use cases.

Loops are very useful for repetitive tasks such as iterating over arrays, reading user input, computing accumulations, and printing specific patterns. Choosing the right type of loop will make your code more efficient and easier to understand. However, programmers must be careful not to create infinite loops (unbounded loops) that can cause a program to hang.

Loop Types in C++

1. For Loop

for (initialization; condition; update) {
    // code that is repeated
}

2. While Loop

while (condition) {
    // code that is repeated while condition is true
}

3. Do-While Loop

do {
    // code that is repeated at least once
} while (condition);

4. Range-Based For Loop (C++11)

for (type variable : container) {
    // code for each element
}

Code Example

#include <iostream>
using namespace std;

int main() {
    // Basic for loop
    cout << "=== For Loop ===" << endl;
    for (int i = 1; i <= 5; i++) {
        cout << "Iteration " << i << endl;
    }

    // For loop with step 2
    cout << "\n=== For Loop (step 2) ===" << endl;
    for (int i = 0; i <= 10; i += 2) {
        cout << i << " ";
    }
    cout << endl;

    // For loop backward
    cout << "\n=== For Loop (backward) ===" << endl;
    for (int i = 5; i >= 1; i--) {
        cout << i << "..." << endl;
    }
    cout << "GO!" << endl;

    // While loop
    cout << "\n=== While Loop ===" << endl;
    int count = 1;
    while (count <= 5) {
        cout << "Count: " << count << endl;
        count++;
    }

    // Do-while loop
    cout << "\n=== Do-While Loop ===" endl;
    int choice;
    do {
        cout << "\n1. Start" << endl;
        cout << "2. Settings" << endl;
        cout << "0. Exit" << endl;
        cout << "Choice (0-2): ";
        cin >> choice;
        if (choice == 1) {
            cout << "Game started!" << endl;
        } else if (choice == 2) {
            cout << "Settings opened." << endl;
        } else if (choice != 0) {
            cout << "Invalid choice!" << endl;
        }
    } while (choice != 0);
    cout << "Program finished." << endl;

    // Nested loop - printing a star pattern
    cout << "\n=== Nested Loop (Star Pattern) ===" << endl;
    int rows = 5;
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }

    // Number pattern
    cout << "\n=== Number Pattern ===" << endl;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }

    // Infinite loop (with break)
    cout << "\n=== Infinite Loop with Break ===" << endl;
    int number;
    int total = 0;
    while (true) {
        cout << "Enter a number (0 to stop): ";
        cin >> number;
        if (number == 0) break;
        total += number;
        cout << "Current total: " << total << endl;
    }
    cout << "Final total: " << total << endl;

    // Continue statement
    cout << "\n=== Continue (Skip Even Numbers) ===" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;
        cout << i << " ";
    }
    cout << endl;

    // Labeled break (using goto)
    cout << "\n=== Labeled Break (goto) ===" << endl;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i == 2 && j == 2) {
                cout << "\nFound at (" << i << "," << j << "), exiting all!" << endl;
                goto done;
            }
            cout << "(" << i << "," << j << ") ";
        }
        cout << endl;
    }
    done:
    cout << "Program finished." << endl;

    return 0;
}

Code Explanation

  • For Loop: Best suited for iteration with a known number of repetitions. It consists of three parts: initialization, condition, and update. All three parts can be left empty.
  • While Loop: Evaluates the condition before each iteration. Suitable for situations where the number of iterations is not known in advance. Be careful not to forget updating the control variable.
  • Do-While Loop: Similar to while, but it evaluates the condition after the code block has run. Guarantees at least one execution. Ideal for user input menus.
  • Range-Based For: Automatically iterates over the elements of a container (array, vector, string). Syntax: for (auto x : container). Use & for references: for (auto &x : container).
  • Nested Loop: A loop inside a loop. Useful for 2D operations such as patterns, matrices, and layered searches.
  • Break: Stops the loop and continues with the statement after the loop.
  • Continue: Skips the rest of the current iteration and moves on to the next iteration.
  • Labeled Break (goto): Breaks out of a nested loop using goto. Useful, but it must be used with caution.

Everyday Use Cases

Factorial Calculator:

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "=== Factorial Calculator ===" << endl;
    cout << "Enter a positive number: ";
    cin >> n;

    if (n < 0) {
        cout << "Error: The number must be positive!" << endl;
        return 1;
    }

    // Using a for loop
    long long factorial = 1;
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
    cout << n << "! = " << factorial << endl;

    // Displaying the calculation process
    cout << "\nProcess: ";
    for (int i = 1; i <= n; i++) {
        cout << i;
        if (i < n) cout << " x ";
    }
    cout << " = " << factorial << endl;

    return 0;
}

Summing Numbers from an Array:

#include <iostream>
using namespace std;

int main() {
    int data[] = {12, 45, 7, 23, 56, 89, 34};
    int size = sizeof(data) / sizeof(data[0]);

    cout << "=== Computing Data Statistics ===" << endl;

    // Displaying the data
    cout << "Data: ";
    for (int i = 0; i < size; i++) {
        cout << data[i];
        if (i < size - 1) cout << ", ";
    }
    cout << endl;

    // Computing the sum, min, max, and average
    int total = 0;
    int minVal = data[0];
    int maxVal = data[0];

    for (int i = 0; i < size; i++) {
        total += data[i];
        if (data[i] < minVal) minVal = data[i];
        if (data[i] > maxVal) maxVal = data[i];
    }

    double average = (double)total / size;

    cout << "\nTotal    : " << total << endl;
    cout << "Minimum  : " << minVal << endl;
    cout << "Maximum  : " << maxVal << endl;
    cout << "Average  : " << average << endl;

    // Counting odd numbers
    cout << "\nOdd numbers: ";
    int oddCount = 0;
    for (int i = 0; i < size; i++) {
        if (data[i] % 2 != 0) {
            cout << data[i] << " ";
            oddCount++;
        }
    }
    cout << "\nCount of odd numbers: " << oddCount << endl;

    return 0;
}

Conclusion

C++ provides four types of loops: for for iteration with a known number of repetitions, while for a condition checked before execution, do-while for at least one execution, and range-based for for iterating over containers. Nested loops enable 2D operations. Use break to exit a loop and continue to skip the current iteration. Always make sure a loop has a clear stopping condition to avoid infinite loops.