Paramclasses Academy - Blog

Tutorials Details

What is Loops in C++

What is Loops in C++

October 15, 2026

1. What is a loop in C++?

A loop is a control-flow statement that executes a block of code repeatedly while a condition is satisfied, or until a specified stopping point is reached.

Suppose you want to print the numbers from 1 to 5.

Without a loop, you might write:

#include <iostream>
using namespace std;

int main() {
    cout << 1 << endl;
    cout << 2 << endl;
    cout << 3 << endl;
    cout << 4 << endl;
    cout << 5 << endl;

    return 0;
}

This works, but repeating the same statement becomes inconvenient when you need to print 100 or 1,000 numbers.

Using a loop:

#include <iostream>
using namespace std;

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

    return 0;
}

Output

1
2
3
4
5

The loop repeats the cout statement five times, changing the value of i on each iteration.

Learning objectives

By the end of this module, you should be able to:

  • Understand loop execution and iterations.

  • Use for, while, and do-while loops.

  • Create nested loops and simple number patterns.

  • Control execution using break and continue.

  • Identify infinite loops and off-by-one errors.

  • Solve beginner-level programming problems using loops.

2. Types of loops in C++

C++ provides three commonly used loop statements.

1. for loop

Best when the number of repetitions is known or a counter controls the repetition.

Example: Print numbers from 1 to 10.

2. while loop

Best when repetition depends on a condition and the number of iterations may not be known in advance.

Example: Keep reading input until the user enters 0.

3. do-while loop

Best when the code must execute at least once before the condition is checked.

Example: Display a menu before asking whether to repeat it.

3. The for loop

The for loop combines initialization, a condition, and an update in one statement.

Syntax

for (initialization; condition; update) {
    // Code to repeat
}

The three parts have different responsibilities:

Part

Purpose

Example

Initialization

Sets the starting value

int i = 1

Condition

Determines whether the loop continues

i <= 5

Update

Changes the loop variable

i++

Example 1: Print numbers from 1 to 5

#include <iostream>
using namespace std;

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

    return 0;
}

Output

1 2 3 4 5

How it executes

Initialize

i = 1

Check

i <= 5

If true: execute the body

Print i

Update

i++ increases i by 1

Return to the condition check. If false, exit the loop.

The initialization runs once. The condition is checked before each iteration. After the body runs, the update executes.

Example 2: Print even numbers from 2 to 10

#include <iostream>
using namespace std;

int main() {
    for (int i = 2; i <= 10; i += 2) {
        cout << i << " ";
    }

    return 0;
}

Output

2 4 6 8 10

Here, i += 2 adds 2 to i after every iteration.

Example 3: Calculate the sum of the first 5 natural numbers

#include <iostream>
using namespace std;

int main() {
    int sum = 0;

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

    cout << "Sum = " << sum;

    return 0;
}

Output

Sum = 15

The variable sum accumulates the values \(1+2+3+4+5=15\).

4. The while loop

A while loop checks its condition before executing its body. If the condition is initially false, the body does not run at all.

Syntax

while (condition) {
    // Code to repeat
}

Example 1: Print numbers from 1 to 5

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    while (i <= 5) {
        cout << i << " ";
        i++;
    }

    return 0;
}

Output

1 2 3 4 5

The variable i is initialized before the loop. Inside the loop, i++ moves it toward the stopping condition.

Example 2: Countdown

#include <iostream>
using namespace std;

int main() {
    int count = 5;

    while (count >= 1) {
        cout << count << " ";
        count--;
    }

    cout << "Go!";

    return 0;
}

Output

5 4 3 2 1 Go!

Example 3: Read numbers until the user enters 0

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter a number (0 to stop): ";
    cin >> number;

    while (number != 0) {
        cout << "You entered: " << number << endl;
        cout << "Enter a number (0 to stop): ";
        cin >> number;
    }

    cout << "Program ended.";

    return 0;
}

Example run

Enter a number (0 to stop): 7
You entered: 7
Enter a number (0 to stop): 3
You entered: 3
Enter a number (0 to stop): 0
Program ended.

This example demonstrates a condition-controlled loop: the number of iterations depends on user input.

5. The do-while loop

A do-while loop executes the body first and checks the condition afterward. Therefore, its body runs at least once, even if the condition is false initially.

Syntax

do {
    // Code to repeat
} while (condition);

Notice the semicolon after while (condition);. It is required.

Example 1: Basic do-while loop

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << i << " ";
        i++;
    } while (i <= 5);

    return 0;
}

Output

1 2 3 4 5

Example 2: Demonstrate that it executes at least once

#include <iostream>
using namespace std;

int main() {
    int i = 10;

    do {
        cout << "Executed once";
    } while (i < 5);

    return 0;
}

Output

Executed once

Even though i < 5 is false, the message prints once because the condition is checked after the body.

Example 3: Simple menu

#include <iostream>
using namespace std;

int main() {
    int choice;

    do {
        cout << "\n1. Say Hello";
        cout << "\n2. Exit";
        cout << "\nEnter choice: ";
        cin >> choice;

        if (choice == 1) {
            cout << "Hello!";
        }
    } while (choice != 2);

    cout << "\nGoodbye!";

    return 0;
}

Example run

1. Say Hello
2. Exit
Enter choice: 1
Hello!
1. Say Hello
2. Exit
Enter choice: 2
Goodbye!

This pattern is useful for menus that should be displayed before the program checks whether the user wants to exit.

6. Difference between for, while, and do-while

Feature

for

while

do-while

Condition checked

Before body

Before body

After body

Minimum executions

0

0

1

Initialization

Often in header

Usually before loop

Usually before loop

Update

Often in header

Usually in body

Usually in body

Typical use

Counter-based repetition

Condition-based repetition

Must execute at least once

Remember: These loops can often solve the same problem. Choose the one that makes the logic easiest to understand.

7. Nested loops

A nested loop is a loop inside another loop. The inner loop completes its iterations for each iteration of the outer loop.

Example 1: Print a rectangle of stars

#include <iostream>
using namespace std;

int main() {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 4; col++) {
            cout << "* ";
        }
        cout << endl;
    }

    return 0;
}

Output

* * * *
* * * *
* * * *

The outer loop runs 3 times. For each row, the inner loop prints 4 stars.

Example 2: Print a right triangle

#include <iostream>
using namespace std;

int main() {
    for (int row = 1; row <= 5; row++) {
        for (int col = 1; col <= row; col++) {
            cout << "* ";
        }
        cout << endl;
    }

    return 0;
}

Output

*
* *
* * *
* * * *
* * * * *

The inner loop's stopping condition, col <= row, makes each row one star longer than the previous row.

Example 3: Multiplication table from 1 to 3

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }

    return 0;
}

Output

1   2   3
2   4   6
3   6   9

\t inserts a tab between values. Exact spacing may vary by console.

Important: If an outer loop runs \(m\) times and an inner loop runs \(n\) times for every outer iteration, the inner body runs \(m \times n\) times.

8. The break statement

The break statement immediately terminates the nearest enclosing loop. Execution continues with the first statement after that loop.

Example: Stop at 5

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;
        }

        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4

When i == 5, break exits the loop before 5 is printed.

When should you use break?

  • Stop searching after finding a target.

  • Exit a loop when the user requests it.

  • End a loop immediately when a special condition occurs.

9. The continue statement

The continue statement skips the remainder of the current iteration and proceeds to the next iteration of the nearest enclosing loop.

Example: Skip the number 5

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue;
        }

        cout << i << " ";
    }

    return 0;
}

Output

1 2 3 4 6 7 8 9 10

The loop continues running, but the output statement is skipped when i == 5.

break vs continue

Statement

Effect

break

Ends the loop completely

continue

Skips the current iteration and continues the loop

Caution with while loops: Make sure the loop variable still changes when continue is executed. Otherwise, the loop can become infinite.

For example, placing continue before i++ in a while loop may prevent i from ever reaching its stopping value.

10. Infinite loops

An infinite loop continues indefinitely because its stopping condition never becomes false, or because the loop intentionally has no built-in stopping condition.

Incorrect example

int i = 1;

while (i <= 5) {
    cout << i << " ";
}

Here, i never changes. The condition i <= 5 stays true forever.

Corrected example

int i = 1;

while (i <= 5) {
    cout << i << " ";
    i++;
}

Now the value increases on each iteration, and the loop terminates when i becomes 6.

Intentional infinite loop

while (true) {
    // Repeat until a break condition is reached
}

This pattern is sometimes used in event-driven or menu-based programs, but it should include a suitable exit mechanism when required.

11. Common mistakes in loops

Mistake 1: Off-by-one errors

Using i < 5 instead of i <= 5 changes how many iterations execute.

for (int i = 1; i < 5; i++)

This executes for 1, 2, 3, and 4 — not 5.

Mistake 2: Forgetting the update

A counter-based while loop can become infinite if its counter never changes.

Mistake 3: Missing the do-while semicolon

Correct: } while (condition);

The semicolon is part of the do-while statement.

Mistake 4: Confusing break and continue

break exits the loop. continue skips only the current iteration.

Mistake 5: Incorrect nested-loop variables

Use different variables such as i and j to make the outer and inner loop logic easier to follow.

12. Mini project — Number guessing game

This small project combines a while loop, conditional statements, user input, and a counter.

Goal

The user must guess a fixed number. The program repeats until the correct number is entered and then displays the number of attempts.

Code

#include <iostream>
using namespace std;

int main() {
    const int secretNumber = 7;
    int guess;
    int attempts = 0;

    cout << "Guess the number (1 to 10): ";

    while (true) {
        cin >> guess;
        attempts++;

        if (guess == secretNumber) {
            cout << "Correct! You won in "
                 << attempts << " attempts.";
            break;
        } else if (guess < secretNumber) {
            cout << "Too low. Try again: ";
        } else {
            cout << "Too high. Try again: ";
        }
    }

    return 0;
}

Example run

Guess the number (1 to 10): 4
Too low. Try again: 9
Too high. Try again: 7
Correct! You won in 3 attempts.

What you learned from the project

  • while (true) repeats until break executes.

  • if, else if, and else compare the guess.

  • attempts++ counts the guesses.

  • break terminates the loop when the answer is correct.

For an extended version, add input validation so that guesses outside the range 1–10 do not count as valid attempts.

13. Hands-on exercises

Try solving these without looking at the solutions first.

Exercise 1

Print numbers from 1 to 100

Write a for loop that prints all integers from 1 through 100.

Hint: Initialize a counter at 1 and use a condition that includes 100.

Exercise 2

Calculate the factorial

Write a program that calculates \(5! = 5 \times 4 \times 3 \times 2 \times 1\).

Expected output: Factorial = 120

Exercise 3

Print a multiplication table

Accept an integer from the user and print its multiplication table from 1 to 10.

Hint: Use a counter-based loop and multiply the input by the counter.

Exercise 4

Sum of even numbers

Calculate the sum of all even numbers from 1 through 50.

Expected output: Sum = 650

Exercise 5

Print a number triangle

Use nested loops to produce this pattern:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

14. Module summary

You have now covered the core loop constructs in C++.

  • for loop: useful for counter-based repetition.

  • while loop: checks the condition before every iteration.

  • do-while loop: checks the condition after executing the body.

  • Nested loops: place one loop inside another to handle rows, columns, and patterns.

  • break: exits the nearest enclosing loop.

  • continue: skips the rest of the current iteration.

  • Infinite-loop prevention: ensure the loop's stopping condition can eventually become false, unless indefinite repetition is intentional.

15. Interactive knowledge-check quiz

Choose an answer for each question, then submit the quiz to check your score.

C++ Loops Quiz

0 of 7 answered

1. Which loop is guaranteed to execute its body at least once?

for

while

do-while

None of these

2. What is the output of for (int i = 1; i <= 3; i++) cout << i; ?

012

123

1234

12

3. What does break do inside a loop?

Skips one iteration

Restarts the program

Terminates the nearest enclosing loop

Increases the counter

4. What does continue do?

Ends the entire program

Skips the rest of the current iteration

Exits all nested loops

Makes the condition true

5. How many times does the inner body run if an outer loop runs 3 times and an inner loop runs 4 times per outer iteration?

3

4

7

12

6. What is a common cause of an unintended infinite while loop?

Using cout

Using braces

Never updating a counter that controls the condition

Declaring an int

7. Which punctuation is required at the end of a do-while statement?

A comma

A semicolon

A colon

No punctuation

Submit quiz

Answer all seven questions to submit your quiz.

Module 5 completion checklist

Your progress

0 / 6

I can write a for loop and explain its three parts.

I can write while and do-while loops.

I understand nested loops and number patterns.

I can use break and continue correctly.

I can identify and fix common infinite-loop errors.

I have attempted the five practice exercises and quiz.