C++ Loops Complete Guide
Iteration Control

C++ Loops: Complete Guide with Examples

Master all C++ loops: for, while, do-while, and range-based for loops. Learn loop control statements, nested loops, infinite loops, and best practices for efficient iteration.

for Loop

Definite Iteration

while Loop

Condition-based

do-while

Post-test Loop

Range-based

C++11 Feature

Introduction to Loops

Loops are fundamental control structures that allow executing a block of code repeatedly. They are essential for processing collections of data, implementing algorithms, and creating interactive programs.

Why Use Loops?
  • Avoid code repetition
  • Process arrays and collections
  • Implement algorithms (searching, sorting)
  • Create menus and interactive programs
  • Handle data in batches
  • Simulate real-world processes
Loop Components
  • Initialization: Set starting point
  • Condition: Test for continuation
  • Update: Modify loop variable
  • Body: Code to execute repeatedly
  • Termination: Condition becomes false
General Loop Flowchart
1
Initialization: Set loop counter/variable
2
Condition Check: Test if loop should continue
3
Execute Body: Run loop statements
4
Update: Modify loop variable
5
Repeat or Exit: Return to step 2 or exit

C++ Loops Comparison

The following table compares all loop types in C++ with their syntax, use cases, and characteristics:

Loop Type Syntax When to Use Characteristics
for Loop for(init; condition; update) { } Definite iteration, known number of repetitions Entry-controlled, compact initialization/update
while Loop while(condition) { } Condition-based, unknown repetitions Entry-controlled, condition checked first
do-while Loop do { } while(condition); Execute at least once, then check condition Exit-controlled, body executes first
Range-based for (C++11) for(type var : collection) { } Iterate over containers (arrays, vectors, etc.) Simplified syntax, no index management
Nested Loops loop { loop { } } Multi-dimensional data, matrix operations Loop inside another loop, careful with complexity
Infinite Loop for(;;) or while(true) Server loops, event-driven programming Runs forever until break or return

1. The for Loop

The for loop is used when the number of iterations is known beforehand. It combines initialization, condition checking, and update in one line.

Basic Syntax
for (initialization; condition; update) {
    // Code to execute repeatedly
}
Basic for Loop Examples
#include <iostream>
using namespace std;

int main() {
    // Example 1: Print numbers 1 to 10
    cout << "Numbers 1 to 10:" << endl;
    for (int i = 1; i <= 10; i++) {
        cout << i << " ";
    }
    cout << endl << endl;
    
    // Example 2: Print even numbers
    cout << "Even numbers 2 to 20:" << endl;
    for (int i = 2; i <= 20; i += 2) {
        cout << i << " ";
    }
    cout << endl << endl;
    
    // Example 3: Countdown from 10 to 1
    cout << "Countdown:" << endl;
    for (int i = 10; i > 0; i--) {
        cout << i << " ";
    }
    cout << "Liftoff!" << endl << endl;
    
    // Example 4: Calculate factorial
    int n = 5;
    long long factorial = 1;
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
    cout << "Factorial of " << n << " = " << factorial << endl << endl;
    
    // Example 5: Sum of numbers
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    cout << "Sum of 1 to 100 = " << sum << endl;
    
    return 0;
}
Advanced for Loop Variations:
  • Multiple variables: for(int i=0, j=10; i<j; i++, j--)
  • Empty initialization: for(; i<10; i++)
  • No update in header: Update inside loop body
  • Infinite loop: for(;;)
Common Mistakes:
  • Semicolon after for: for(...); { }
  • Incorrect loop bounds (off-by-one errors)
  • Modifying loop variable inside body
  • Infinite loops with wrong condition

2. The while Loop

The while loop repeats as long as the condition is true. It's ideal when the number of iterations is unknown.

Basic Syntax
while (condition) {
    // Code to execute while condition is true
}
while Loop Examples
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime>   // For time()
using namespace std;

int main() {
    // Seed random number generator
    srand(time(0));
    
    // Example 1: Basic while loop
    cout << "Example 1: Countdown" << endl;
    int count = 5;
    while (count > 0) {
        cout << count << "... ";
        count--;
    }
    cout << "Liftoff!" << endl << endl;
    
    // Example 2: User input validation
    cout << "Example 2: Input Validation" << endl;
    int number;
    cout << "Enter a positive number: ";
    cin >> number;
    
    while (number <= 0) {
        cout << "Invalid! Enter a positive number: ";
        cin >> number;
    }
    cout << "You entered: " << number << endl << endl;
    
    // Example 3: Sum until sentinel value
    cout << "Example 3: Sum Numbers (enter -1 to stop)" << endl;
    int sum = 0;
    int value = 0;
    
    while (value != -1) {
        sum += value;
        cout << "Enter a number (-1 to stop): ";
        cin >> value;
    }
    cout << "Total sum: " << sum << endl << endl;
    
    // Example 4: Random number guessing game
    cout << "Example 4: Guessing Game" << endl;
    int secret = rand() % 100 + 1; // 1-100
    int guess = 0;
    int attempts = 0;
    
    cout << "Guess a number between 1 and 100" << endl;
    
    while (guess != secret) {
        cout << "Your guess: ";
        cin >> guess;
        attempts++;
        
        if (guess < secret) {
            cout << "Too low!" << endl;
        } else if (guess > secret) {
            cout << "Too high!" << endl;
        }
    }
    
    cout << "Congratulations! You guessed it in " 
         << attempts << " attempts." << endl << endl;
    
    // Example 5: Processing string
    cout << "Example 5: Character Processing" << endl;
    string text = "Hello, World!";
    int index = 0;
    
    while (index < text.length()) {
        cout << "Character " << index << ": " << text[index] << endl;
        index++;
    }
    
    return 0;
}

Key Difference: for vs while

Use for when you know how many times to iterate. Use while when iteration depends on a condition that may change during execution.

3. The do-while Loop

The do-while loop executes the body first, then checks the condition. It guarantees at least one execution.

Basic Syntax
do {
    // Code to execute at least once
} while (condition);
do-while Loop Examples
#include <iostream>
#include <cctype> // For toupper()
using namespace std;

int main() {
    char choice;
    
    // Example 1: Menu system (guaranteed to show at least once)
    cout << "Example 1: Menu System" << endl;
    
    do {
        cout << "\n===== MENU =====" << endl;
        cout << "1. Print Hello" << endl;
        cout << "2. Print Goodbye" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter choice (1-3): ";
        cin >> choice;
        
        switch (choice) {
            case '1':
                cout << "Hello, World!" << endl;
                break;
            case '2':
                cout << "Goodbye, World!" << endl;
                break;
            case '3':
                cout << "Exiting..." << endl;
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
    } while (choice != '3');
    
    cout << endl;
    
    // Example 2: Password validation
    cout << "Example 2: Password Validation" << endl;
    string password;
    bool valid = false;
    
    do {
        cout << "Enter password (minimum 8 characters): ";
        cin >> password;
        
        if (password.length() >= 8) {
            valid = true;
            cout << "Password accepted!" << endl;
        } else {
            cout << "Password too short. Try again." << endl;
        }
    } while (!valid);
    
    cout << endl;
    
    // Example 3: Continue until positive number entered
    cout << "Example 3: Positive Number Input" << endl;
    int number;
    
    do {
        cout << "Enter a positive number: ";
        cin >> number;
        
        if (number <= 0) {
            cout << "Number must be positive!" << endl;
        }
    } while (number <= 0);
    
    cout << "You entered: " << number << endl << endl;
    
    // Example 4: Game replay system
    cout << "Example 4: Game Replay" << endl;
    char playAgain;
    
    do {
        cout << "\n=== Playing Game ===" << endl;
        cout << "Game in progress..." << endl;
        cout << "Game over!" << endl;
        
        cout << "Play again? (Y/N): ";
        cin >> playAgain;
        playAgain = toupper(playAgain);
        
    } while (playAgain == 'Y');
    
    cout << "Thanks for playing!" << endl;
    
    return 0;
}
while Loop
  • Condition checked first
  • May execute zero times
  • Use when iterations unknown
  • Entry-controlled
do-while Loop
  • Body executes first
  • Always executes at least once
  • Use for menus, validation
  • Exit-controlled

4. Range-based for Loop (C++11)

The range-based for loop (introduced in C++11) simplifies iteration over containers like arrays, vectors, and other collections.

Basic Syntax
for (type variable : collection) {
    // Use variable for each element
}
Range-based for Loop Examples
#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <list>
using namespace std;

int main() {
    // Example 1: Iterate over array
    cout << "Example 1: Array Iteration" << endl;
    int numbers[] = {1, 2, 3, 4, 5};
    
    cout << "Array elements: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl << endl;
    
    // Example 2: Iterate over vector
    cout << "Example 2: Vector Iteration" << endl;
    vector<string> fruits = {"Apple", "Banana", "Cherry", "Date"};
    
    cout << "Fruits: ";
    for (const string& fruit : fruits) {
        cout << fruit << " ";
    }
    cout << endl << endl;
    
    // Example 3: Modify elements (use reference)
    cout << "Example 3: Modify Array Elements" << endl;
    int scores[] = {85, 90, 78, 92, 88};
    
    cout << "Original scores: ";
    for (int score : scores) {
        cout << score << " ";
    }
    cout << endl;
    
    // Add bonus points (need reference to modify)
    for (int& score : scores) {
        score += 5; // Add 5 to each score
    }
    
    cout << "Updated scores: ";
    for (int score : scores) {
        cout << score << " ";
    }
    cout << endl << endl;
    
    // Example 4: Iterate over string
    cout << "Example 4: String Character Iteration" << endl;
    string message = "Hello C++";
    
    cout << "Characters: ";
    for (char ch : message) {
        cout << ch << " ";
    }
    cout << endl << endl;
    
    // Example 5: Using auto keyword (C++11)
    cout << "Example 5: Using auto with Range-based for" << endl;
    vector<double> prices = {19.99, 29.99, 9.99, 49.99};
    
    cout << "Prices: ";
    for (auto price : prices) { // auto deduces double
        cout << "$" << price << " ";
    }
    cout << endl << endl;
    
    // Example 6: Range-based for with initializer list
    cout << "Example 6: Direct Initialization" << endl;
    cout << "Squares: ";
    for (int num : {1, 2, 3, 4, 5}) {
        cout << num * num << " ";
    }
    cout << endl << endl;
    
    // Example 7: Using const reference for efficiency
    cout << "Example 7: Const Reference for Large Objects" << endl;
    vector<string> bigData = {"Data1", "Data2", "Data3", "Data4"};
    
    for (const auto& data : bigData) { // Avoids copying
        cout << data << endl;
    }
    
    return 0;
}
Best Practices for Range-based for:
  • Use const auto& for read-only access to avoid copying
  • Use auto& when you need to modify elements
  • Use auto for simple types (int, char, etc.)
  • Not suitable when you need the index position
  • Works with any container that has begin() and end() methods

5. Loop Control Statements

C++ provides special statements to control loop execution: break, continue, and goto (use sparingly).

break Statement

Immediately exits the loop, regardless of condition.

for(int i=0; i<10; i++) {
    if(i == 5) break;
    cout << i << " ";
}
// Output: 0 1 2 3 4
continue Statement

Skips current iteration and proceeds to next.

for(int i=0; i<5; i++) {
    if(i == 2) continue;
    cout << i << " ";
}
// Output: 0 1 3 4
goto Statement

Jumps to labeled statement (avoid in modern C++).

int i=0;
start:
cout << i << " ";
i++;
if(i < 3) goto start;
Loop Control Examples
#include <iostream>
using namespace std;

int main() {
    // Example 1: break statement
    cout << "Example 1: break statement" << endl;
    cout << "Searching for number 7: ";
    for (int i = 1; i <= 10; i++) {
        if (i == 7) {
            cout << "Found! ";
            break; // Exit loop immediately
        }
        cout << i << " ";
    }
    cout << endl << endl;
    
    // Example 2: continue statement
    cout << "Example 2: continue statement" << endl;
    cout << "Odd numbers 1-10: ";
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue; // Skip even numbers
        }
        cout << i << " ";
    }
    cout << endl << endl;
    
    // Example 3: break in nested loops
    cout << "Example 3: break in nested loops" << endl;
    bool found = false;
    
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i * j == 6) {
                cout << "Found pair: " << i << " * " << j << " = 6" << endl;
                found = true;
                break; // Only breaks inner loop
            }
        }
        if (found) break; // Breaks outer loop
    }
    cout << endl;
    
    // Example 4: Practical continue example
    cout << "Example 4: Input validation with continue" << endl;
    int sum = 0;
    
    for (int i = 0; i < 5; i++) {
        int num;
        cout << "Enter positive number " << i+1 << ": ";
        cin >> num;
        
        if (num <= 0) {
            cout << "Invalid. Skipping..." << endl;
            continue; // Skip negative/zero numbers
        }
        
        sum += num;
    }
    
    cout << "Sum of positive numbers: " << sum << endl << endl;
    
    // Example 5: Avoiding goto (better alternative)
    cout << "Example 5: goto alternative" << endl;
    int attempts = 0;
    const int MAX_ATTEMPTS = 3;
    
    while (true) {
        attempts++;
        cout << "Attempt " << attempts << endl;
        
        if (attempts >= MAX_ATTEMPTS) {
            cout << "Max attempts reached!" << endl;
            break; // Better than goto
        }
        
        // Simulate some operation
        bool success = false; // Change to test
        
        if (success) {
            cout << "Success!" << endl;
            break;
        }
    }
    
    return 0;
}
Avoid goto Statement: The goto statement can make code difficult to read and maintain. Use structured control flow (break, continue, functions) instead. goto is rarely needed in modern C++.

6. Nested Loops

A loop inside another loop is called a nested loop. Useful for multi-dimensional data, matrices, and complex patterns.

Nested Loop Examples
#include <iostream>
using namespace std;

int main() {
    // Example 1: Multiplication table
    cout << "Example 1: Multiplication Table" << endl;
    for (int i = 1; i <= 10; i++) {
        for (int j = 1; j <= 10; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }
    cout << endl;
    
    // Example 2: Pattern printing (right triangle)
    cout << "Example 2: Star Pattern" << endl;
    int rows = 5;
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    cout << endl;
    
    // Example 3: 2D array processing
    cout << "Example 3: 2D Array Processing" << endl;
    const int ROWS = 3;
    const int COLS = 4;
    int matrix[ROWS][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    
    cout << "Matrix elements:" << endl;
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    cout << endl;
    
    // Example 4: Sum of each row
    cout << "Example 4: Row Sums" << endl;
    for (int i = 0; i < ROWS; i++) {
        int rowSum = 0;
        for (int j = 0; j < COLS; j++) {
            rowSum += matrix[i][j];
        }
        cout << "Sum of row " << i+1 << ": " << rowSum << endl;
    }
    cout << endl;
    
    // Example 5: Different loop types nested
    cout << "Example 5: Mixed Nested Loops" << endl;
    int i = 1;
    while (i <= 3) {
        cout << "Outer loop iteration " << i << ":" << endl;
        
        for (int j = 1; j <= 2; j++) {
            cout << "  Inner for loop: " << j << endl;
        }
        
        i++;
    }
    
    return 0;
}
Nested Loop Performance:
  • Time complexity: O(n²) for doubly nested loops
  • Be careful with deeply nested loops (3+ levels)
  • Consider alternative algorithms for large datasets
  • Use meaningful variable names (i, j, k for indices)
  • Break complex nested loops into functions

7. Infinite Loops

Infinite loops run forever unless explicitly terminated. They're useful for servers, games, and event-driven programs.

Creating Infinite Loops
// Method 1: for loop
for (;;) {
    // Infinite loop
}

// Method 2: while loop
while (true) {
    // Infinite loop
}

// Method 3: do-while loop
do {
    // Infinite loop
} while (true);
Breaking Infinite Loops
while (true) {
    // Get user input
    char command;
    cin >> command;
    
    if (command == 'q') {
        break; // Exit loop
    }
    
    // Process command
}
Infinite Loop Examples
#include <iostream>
#include <cstdlib> // For system()
#include <ctime>   // For time()
#ifdef _WIN32
#include <windows.h> // For Sleep()
#else
#include <unistd.h> // For sleep()
#endif
using namespace std;

void clearScreen() {
    #ifdef _WIN32
    system("cls");
    #else
    system("clear");
    #endif
}

int main() {
    // Example 1: Simple infinite loop with break
    cout << "Example 1: Counter with Break" << endl;
    int count = 0;
    
    while (true) {
        cout << "Count: " << count++ << endl;
        
        if (count > 5) {
            cout << "Breaking loop at count 5" << endl;
            break;
        }
    }
    cout << endl;
    
    // Example 2: Interactive menu system
    cout << "Example 2: Interactive Menu (Press 'q' to quit)" << endl;
    char choice;
    
    while (true) {
        cout << "\n===== MENU =====" << endl;
        cout << "1. Say Hello" << endl;
        cout << "2. Show Time" << endl;
        cout << "3. Clear Screen" << endl;
        cout << "q. Quit" << endl;
        cout << "Enter choice: ";
        cin >> choice;
        
        if (choice == 'q' || choice == 'Q') {
            cout << "Goodbye!" << endl;
            break;
        }
        
        switch (choice) {
            case '1':
                cout << "Hello, User!" << endl;
                break;
            case '2':
                cout << "Current time: " << time(0) << " seconds since epoch" << endl;
                break;
            case '3':
                clearScreen();
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
    }
    
    // Example 3: Game loop
    cout << "\nExample 3: Simple Game Loop" << endl;
    bool gameRunning = true;
    int score = 0;
    
    while (gameRunning) {
        cout << "\n=== GAME ===" << endl;
        cout << "Score: " << score << endl;
        cout << "1. Add 10 points" << endl;
        cout << "2. Lose 5 points" << endl;
        cout << "3. Quit game" << endl;
        cout << "Choice: ";
        
        int gameChoice;
        cin >> gameChoice;
        
        switch (gameChoice) {
            case 1:
                score += 10;
                cout << "Added 10 points!" << endl;
                break;
            case 2:
                score -= 5;
                cout << "Lost 5 points!" << endl;
                break;
            case 3:
                gameRunning = false;
                cout << "Game over! Final score: " << score << endl;
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
        
        // Simple "animation" delay
        #ifdef _WIN32
        Sleep(500); // Windows: milliseconds
        #else
        usleep(500000); // Unix: microseconds
        #endif
    }
    
    // Example 4: Server simulation
    cout << "\nExample 4: Server Loop Simulation" << endl;
    cout << "Server starting... (simulated with counter)" << endl;
    
    for (int i = 1; i <= 10; i++) {
        cout << "Server running... Cycle " << i << endl;
        
        #ifdef _WIN32
        Sleep(100); // Shorter delay
        #else
        usleep(100000);
        #endif
        
        // Simulate server stop condition
        if (i == 10) {
            cout << "Server shutting down..." << endl;
        }
    }
    
    return 0;
}
Infinite Loop Dangers:
  • Always provide an exit condition (break, return)
  • Accidental infinite loops can freeze programs
  • Use with caution in production code
  • Test exit conditions thoroughly
  • Consider using timeouts for safety

8. Best Practices and Common Mistakes

Best Practices
  • Use meaningful loop variable names
  • Prefer range-based for loops for containers
  • Keep loops short and focused
  • Move complex logic to separate functions
  • Use const reference for read-only access
  • Initialize variables before loops
  • Use prefix increment (++i) in for loops
Common Mistakes
  • Off-by-one errors in loop bounds
  • Infinite loops without exit condition
  • Modifying loop variable inside body
  • Using float/double in loop conditions
  • Nested loops with wrong variable names
  • Forgetting to update loop variable
  • Missing braces for multi-line bodies
Good vs Bad Practices
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // BAD PRACTICE: Poor loop structure
    cout << "=== BAD PRACTICES ===" << endl;
    
    // 1. Off-by-one error
    int arr[] = {1, 2, 3, 4, 5};
    // BAD: i <= 5 (should be i < 5)
    for (int i = 0; i <= 5; i++) {
        cout << arr[i] << " "; // Index out of bounds!
    }
    cout << endl;
    
    // 2. Modifying loop variable (confusing)
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            i = 8; // Skips iterations 6-8
        }
        cout << i << " ";
    }
    cout << endl;
    
    // 3. Float in loop condition (precision issues)
    for (float f = 0.0; f != 1.0; f += 0.1) {
        // May never terminate due to floating point precision
        cout << f << " ";
    }
    cout << endl;
    
    cout << "\n=== GOOD PRACTICES ===" << endl;
    
    // 1. Correct bounds
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // 2. Use break instead of modifying i
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            // Skip to end or use different approach
            continue;
        }
        cout << i << " ";
    }
    cout << endl;
    
    // 3. Use integer counters for loops
    for (int i = 0; i <= 10; i++) {
        float f = i * 0.1;
        cout << f << " ";
    }
    cout << endl;
    
    // 4. Range-based for for containers
    vector<int> numbers = {10, 20, 30, 40, 50};
    cout << "Vector elements: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // 5. Meaningful variable names
    const int NUM_STUDENTS = 5;
    int scores[NUM_STUDENTS] = {85, 92, 78, 90, 88};
    
    int totalScore = 0;
    for (int student = 0; student < NUM_STUDENTS; student++) {
        totalScore += scores[student];
    }
    double average = static_cast<double>(totalScore) / NUM_STUDENTS;
    cout << "Average score: " << average << endl;
    
    // 6. Loop optimization: Move invariant code outside
    const double PI = 3.14159;
    double radius = 5.0;
    
    // BAD: Calculating PI * radius in each iteration
    for (int i = 0; i < 10; i++) {
        double area = PI * radius * radius; // Same calculation every time
        cout << "Area: " << area << endl;
    }
    
    // GOOD: Calculate once
    double area = PI * radius * radius;
    for (int i = 0; i < 10; i++) {
        cout << "Area: " << area << endl;
    }
    
    return 0;
}