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

C++ Tutorial · Loops

Loops repeat work until a condition ends them. This guide covers every loop form in modern C++, loop control statements, and patterns that avoid infinite loops and off-by-one mistakes.

C++ loops infographic: for loop, while loop, do-while loop syntax, flowcharts, break and continue, and nested loops comparison
C++ loops visual guide — for, while, and do-while loops with flowcharts, break/continue, and when to use each loop type for iteration and interview practice.

What you will learn

  • Choose for, while, or do-while for each problem
  • Use range-based for with arrays and containers
  • Control loops with break and continue
  • Nest loops for matrices and combinations
  • Recognize infinite loop causes and fixes

Why this topic matters

Iteration dominates algorithms and interview tasks (arrays, strings, patterns). Loop fluency speeds up everything after this chapter.

Key terms & indexing

C++ for loop C++ while loop range-based for nested loops C++

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
}

Examples

1. Print 1 to 10
for (int i = 1; i <= 10; i++)
    cout << i << " ";
2. Even numbers
for (int i = 2; i <= 20; i += 2)
    cout << i << " ";
3. Countdown
for (int i = 10; i > 0; i--)
    cout << i << " ";
4. Factorial
int n = 5, f = 1;
for (int i = 1; i <= n; i++) f *= i;
5. Sum 1–100
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
6. for(;;)
for (;;) { break; }
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
}

Examples

1. Countdown
int c = 5;
while (c > 0) cout << c--;
2. Positive input
int n; cin >> n;
while (n <= 0) cin >> n;
3. Sum until -1
int s = 0, v = 0;
while (v != -1) { s += v; cin >> v; }
4. Guess number
int sec = 7, g = 0;
while (g != sec) cin >> g;
5. String index
string t = "Hi"; int i = 0;
while (i < t.length()) cout << t[i++];
6. while(true)
while (true) { if (done) break; }

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);

Examples

1. Menu loop
char ch;
do {
    cout << "Menu...";
    cin >> ch;
} while (ch != '3');
2. Password length
string pwd;
do { cin >> pwd; }
while (pwd.length() < 8);
3. Positive number
int n;
do { cin >> n; }
while (n <= 0);
4. Play again
char again;
do { /* game */ cin >> again; }
while (again == 'Y');
5. At least once
int x = 0;
do { x++; } while (x < 1);
6. do-while syntax
do { /* body */ }
while (condition);
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
}

Examples

1. int array
int a[] = {1,2,3,4,5};
for (int n : a) cout << n;
2. vector strings
vector<string> v = {"A","B"};
for (const string& s : v)
    cout << s;
3. Modify with ref
int sc[] = {80,90};
for (int& x : sc) x += 5;
4. string chars
string msg = "Hi";
for (char c : msg) cout << c;
5. auto keyword
vector<double> p = {9.9, 19.9};
for (auto price : p) cout << price;
6. Initializer list
for (int n : {1,2,3,4,5})
    cout << n * n;
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;

Examples

1. break on 7
for (int i = 1; i <= 10; i++)
    if (i == 7) break;
2. continue odds
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;
    cout << i;
}
3. break inner loop
for (int i = 1; i <= 3; i++)
    for (int j = 1; j <= 3; j++)
        if (i*j == 6) break;
4. break both loops
bool found = false;
for (int i = 1; i <= 3 && !found; i++)
    for (int j = 1; j <= 3; j++)
        if (i*j == 6) found = true;
5. skip invalid input
for (int i = 0; i < 5; i++) {
    int n; cin >> n;
    if (n <= 0) continue;
    sum += n;
}
6. break not goto
while (true) {
    if (attempts >= 3) break;
}
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.

Examples

1. Times table cell
for (int i = 1; i <= 10; i++)
    for (int j = 1; j <= 10; j++)
        cout << i*j << "	";
2. Star triangle
for (int i = 1; i <= 5; i++)
    for (int j = 1; j <= i; j++)
        cout << "* ";
3. 2D array print
int m[3][4];
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 4; j++)
        cout << m[i][j];
4. Row sum
for (int i = 0; i < ROWS; i++) {
    int rs = 0;
    for (int j = 0; j < COLS; j++) rs += m[i][j];
}
5. while + for
int i = 1;
while (i <= 3) {
    for (int j = 1; j <= 2; j++) cout << j;
    i++;
}
6. Nested complexity
// O(n^2) for double nested loop
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
}

Examples

1. while(true) + break
int c = 0;
while (true) {
    if (++c > 5) break;
}
2. Menu quit 'q'
while (true) {
    char cmd; cin >> cmd;
    if (cmd == 'q') break;
}
3. Game loop flag
bool running = true;
while (running) { /* game */ }
4. for(;;)
for (;;) {
    if (exit) break;
}
5. do-while(true)
do { /* body */ } while (true);
6. Server cycle
for (int i = 1; i <= 10; i++)
    cout << "Cycle " << i;
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

Examples

1. Correct bounds
int arr[5];
for (int i = 0; i < 5; i++)
    cout << arr[i];
2. Off-by-one BAD
// BAD: i <= 5 for size 5
for (int i = 0; i <= 5; i++)
3. Use continue
for (int i = 0; i < 10; i++) {
    if (i == 5) continue;
    cout << i;
}
4. int counter not float
for (int i = 0; i <= 10; i++)
    cout << i * 0.1;
5. Range-based for
vector<int> v = {10,20,30};
for (int n : v) cout << n;
6. Hoist invariant
double area = PI * r * r;
for (int i = 0; i < 10; i++)
    cout << area;

Frequently asked questions

Which loop runs at least once?

do-while checks the condition after the body, so it always executes once.

What is range-based for?

for (auto x : container) iterates elements without manual index—preferred for STL containers.

How do I avoid off-by-one errors?

Be explicit about < vs <=, start indices at 0, and use container.size() carefully in loop bounds.