C++ Basics · Chapter 4

Loops and Iteration in C++: while, for, do-while

Learn how to make your programs repeat tasks efficiently using while, for, and do-while loops. Master break, continue, and common loop patterns.

By Arj Updated July 2025 14 min read No prior experience needed
What you'll learn
  • What loops are and why they are essential
  • How to use while, for, and do-while loops
  • How to control loops with break and continue
  • Common patterns: counting, summing, and nested loops
  • How to avoid infinite loops and off-by-one errors

1Why use loops?

Loops allow you to repeat a block of code multiple times. Instead of writing the same code again and again, you let the loop do the repetition for you.

Without a loop:

cpp
cout << "Hello" << endl;
cout << "Hello" << endl;
cout << "Hello" << endl;

With a loop:

cpp
for (int i = 0; i < 3; i++) {
    cout << "Hello" << endl;
}

Loops are one of the most powerful tools in programming. They let you:

  • Process lists of data (arrays, vectors, files)
  • Repeat an action a specific number of times
  • Keep running until a condition changes (like user input)
  • Build complex patterns and structures

2The while loop

The while loop checks the condition before each iteration. If the condition is false initially, the loop body never runs.

Syntax:

cpp
while (condition) {
    // code block
}

Example – printing numbers 1 to 5:

cpp
int i = 1;
while (i <= 5) {
    cout << i << endl;
    i++;
}
Output1 2 3 4 5
Infinite loop danger
If you forget to update the loop variable (e.g., i++), the condition will always be true and the loop will run forever. Always ensure the condition eventually becomes false.

3The for loop

A for loop is ideal when the number of iterations is known in advance. It combines initialization, condition, and update in one line.

Syntax:

cpp
for (initialization; condition; update) {
    // code block
}

Example – printing numbers 1 to 5:

cpp
for (int i = 1; i <= 5; i++) {
    cout << "Number: " << i << endl;
}
OutputNumber: 1 Number: 2 Number: 3 Number: 4 Number: 5

The for loop does exactly the same thing as the while example but is more compact and is the preferred style when you know exactly how many times to iterate.

4The do-while loop

The do-while loop checks the condition after each iteration. This guarantees that the loop body runs at least once.

Syntax:

cpp
do {
    // code block
} while (condition);

Example – printing numbers 1 to 5:

cpp
int i = 1;
do {
    cout << i << endl;
    i++;
} while (i <= 5);
Output1 2 3 4 5
When to use do-while
Use do-while when you need the loop to run at least once regardless of the condition. A classic example is a menu that must display at least once before asking the user to exit.

5Example: Sum of first N numbers

Here is a practical example that calculates the sum of numbers from 1 to N using a for loop.

cpp
int n;
cout << "Enter a number: ";
cin >> n;

int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}

cout << "Sum: " << sum << endl;
Sample runEnter a number: 5 Sum: 15

This code adds 1 + 2 + 3 + 4 + 5 = 15. The sum += i shorthand is equivalent to sum = sum + i.

6break and continue

break exits the loop immediately, even if the condition is still true. continue skips the current iteration and jumps to the next one.

break example

cpp
for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    cout << i << " ";
}
Output1 2 3 4

continue example

cpp
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    cout << i << " ";
}
Output1 2 4 5

7Nested loops

You can put one loop inside another. This is useful for working with grids, tables, or any problem that requires two dimensions.

Example – multiplication table (5x5):

cpp
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        cout << i * j << "\t";
    }
    cout << endl;
}
Output1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Nested loop performance
Be careful with nested loops. If the outer loop runs N times and the inner loop runs M times, the total iterations are N × M. This can become slow for large values.

8Common loop patterns

1. Counting from 0 to N-1

cpp
for (int i = 0; i < 10; i++) {
    cout << i << " ";
}
Output0 1 2 3 4 5 6 7 8 9

2. Sum of even numbers (2 to 100)

cpp
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
    sum += i;
}
cout << sum;
Output2550

3. Reverse loop (10 down to 1)

cpp
for (int i = 10; i >= 1; i--) {
    cout << i << " ";
}
Output10 9 8 7 6 5 4 3 2 1

9Common mistakes to avoid

1. Forgetting to update the loop variable
This creates an infinite loop. Always ensure the loop variable changes in a way that eventually makes the condition false.
2. Off-by-one errors
Using <= when you should use < (or vice versa). For example, i < 10 runs 10 times (0–9), while i <= 10 runs 11 times (0–10).
3. Misplaced braces
Without braces, only the first statement after the loop is repeated. Always use braces, even for one-line loops, when you are learning.

10Mini exercises

Try these yourself
  1. Print numbers from 1 to 20 using a while loop.
  2. Find the factorial of a number using a for loop. (Factorial of 5 = 5 × 4 × 3 × 2 × 1 = 120)
  3. Use a do-while loop to ask the user for a number until they enter a positive number.
  4. Create a pattern like this using nested loops:
    *
    **
    ***
    ****

Hint: For the pattern, the outer loop controls rows, and the inner loop controls stars in each row.

11Quiz yourself

Loops Quiz
Question 1 of 10
Coming up next
Arrays and Vectors
Learn how to store and work with lists of data using arrays and vectors in C++.
Continue to Chapter 5

Stop wrestling with confusion.

Join thousands of students mastering Computer Science without the academic jargon.

From syntax to systems. We break down the hardest ideas in computer science so you can actually build things.

© 2026 Painless Programming. Built for students.
Scroll to Top