Loops in C++ (for, while, do-while)

9/12/2025
All Articles

Loops in C++ Tutorial (for, while, do-while)

Loops in C++ (for, while, do-while)

Loops in C++ (for, while, do-while)

Loops are used in C++ to execute a block of code repeatedly as long as a specified condition is true. They help reduce code duplication and improve efficiency.

C++ provides three main types of loops:

  • for loop

  • while loop

  • do-while loop


Below is details of 3 type of loop

 

🔹 for Loo

The for loop is used when you know in advance how many times you want to execute a block of code.

Syntax:

for (initialization; condition; update) {
    // Code block to be executed
}

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << "Iteration " << i << endl;
    }
    return 0;
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

🔹 while Loop

The while loop is used when the number of iterations is not known in advance. It checks the condition before executing the block.

Syntax:

while (condition) {
    // Code block to be executed
}

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    while (i <= 5) {
        cout << "Iteration " << i << endl;
        i++;
    }
    return 0;
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

🔹 do-while Loop

The do-while loop is similar to the while loop but it executes the block of code at least once, even if the condition is false.

Syntax:

do {
    // Code block to be executed
} while (condition);

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << "Iteration " << i << endl;
        i++;
    } while (i <= 5);
    return 0;
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Best Practices

  • Use for when iteration count is known.

  • Use while for condition-based loops.

  • Use do-while if the loop must run at least once.

  • Always update loop variables to avoid infinite loops.

Article