for, while, and do-while Loops
A loop repeats a block of code until a condition becomes false. C++ provides three loop forms, each suited to a different situation. The for loop is ideal when you know in advance how many times to iterate. The while loop is best when the number of iterations depends on something that changes during execution. The do-while loop guarantees the body runs at least once before the condition is checked. Any of the three can be used for any looping task, but choosing the right form makes the intent obvious.
The for loop
The for loop packs initialization, condition, and update into one line, making the loop control visible at a glance. The general form is:
for (initialization; condition; update)
{
// body — repeated while condition is true
}
// Count from 1 to 5:
for (int i = 1; i <= 5; ++i)
{
std::cout << i << " "; // prints: 1 2 3 4 5
}
// Count down:
for (int i = 5; i >= 1; --i)
{
std::cout << i << " "; // prints: 5 4 3 2 1
}
// Step by 2:
for (int i = 0; i < 10; i += 2)
{
std::cout << i << " "; // prints: 0 2 4 6 8
}Execution order: first the initialization runs once; then the conditionis tested; if true, the body runs; then the update runs; then the condition is tested again. This continues until the condition is false.
Common patterns:
// Iterating over array indices (old style):
int arr[] = {10, 20, 30, 40, 50};
int size = 5;
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
// Summing values:
int sum = 0;
for (int i = 1; i <= 100; ++i) {
sum += i;
}
// sum == 5050
// Multiple variables in for:
for (int i = 0, j = 10; i < j; ++i, --j) {
std::cout << i << "," << j << " ";
// prints: 0,10 1,9 2,8 3,7 4,6
}The while loop
The while loop tests its condition before each iteration. If the condition is false at the very start, the body never runs. Use while when the number of iterations is not known in advance — for example, when processing input until the user types a sentinel value, or until a calculation converges.
// Read positive numbers and sum them; stop on -1
int sum = 0;
int input;
std::cin >> input;
while (input != -1)
{
sum += input;
std::cin >> input;
}
std::cout << "Sum: " << sum << "\n";// Countdown (while form of for):
int n = 5;
while (n > 0)
{
std::cout << n << " ";
--n;
}
// Output: 5 4 3 2 1The do-while loop
The do-while loop tests its condition after the body runs, guaranteeing the body executes at least once. The most natural use case is input validation: ask the user for input, then check if it is valid; if not, ask again.
int value;
do
{
std::cout << "Enter a number between 1 and 10: ";
std::cin >> value;
}
while (value < 1 || value > 10); // re-prompt until valid
std::cout << "You entered: " << value << "\n";Notice the semicolon after the closing condition — this is required for do-while (unlike for and while, which have no semicolon after their condition). Forgetting it is a compile error.
Nested loops
A loop body can contain another loop. The inner loop runs completely for each iteration of the outer loop. This is the standard approach for processing two-dimensional data (matrices, tables) or generating combinations.
// Multiplication table:
for (int row = 1; row <= 5; ++row)
{
for (int col = 1; col <= 5; ++col)
{
std::cout << row * col << "\t";
}
std::cout << "\n";
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// ...Infinite loops and common mistakes
An infinite loop is one whose condition never becomes false — it runs forever (or until the program is killed). Infinite loops are usually bugs, though they are sometimes intentional (game loops, server accept loops) paired with a break to exit. The most common accidental infinite loops:
// Bug: forgot to increment — n never changes
int n = 5;
while (n > 0) {
std::cout << n;
// missing: --n;
}
// Bug: off-by-one in the update — goes past zero without hitting it
for (unsigned int i = 10; i >= 0; --i) { // unsigned can never be < 0!
std::cout << i;
// when i reaches 0 and is decremented, it wraps to 4 billion+
}
// Fix: use signed int, or change condition to i > 0
// Intentional infinite loop with exit:
while (true) {
std::string cmd;
std::cin >> cmd;
if (cmd == "quit") break;
process(cmd);
}Key rules to remember
Use for when the iteration count is known, while when it depends on runtime data
for keeps init/condition/update in one visible line. while is cleaner when those three things are spread out or don't fit the for model.
Use do-while when the body must run at least once
Input validation is the canonical use case: prompt once, check, re-prompt if invalid.
Do not use unsigned variables as loop counters that count down to zero
unsigned can never be negative. i >= 0 is always true for unsigned i, so the loop never exits. Use int or check i > 0.
Every loop that modifies its counter must actually make progress toward the exit condition
Missing the update (forgetting --i or ++i) is the most common infinite-loop bug.