Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

C++ While and Do‑While Loops – Mastering Repetition in Your Code

C++ While and Do‑While Loops – Mastering Repetition in Your Code

This guide explains the while and do‑while loops in C++ with clear examples, flowcharts, and best‑practice tips.

Loops are a cornerstone of efficient programming: they let you execute a block of code repeatedly without duplicating lines. Whether you’re iterating over a range or waiting for user input, choosing the right loop type is crucial for readable, maintainable code.

In C++ there are three primary loop constructs:

  1. for loop – ideal when the number of iterations is known.
  2. while loop – executes while a condition remains true.
  3. do…while loop – guarantees at least one execution before the condition is tested.

While the for loop was covered in a previous tutorial, this article focuses on the while and do…while loops, detailing syntax, execution flow, common pitfalls, and real‑world use cases.


C++ While Loop

The syntax of a while loop is straightforward:

while (condition) {
    // body of the loop
}

The loop evaluates condition before each iteration:

For deeper insight into C++ relational and logical operators, refer to the C++ Relational and Logical Operators guide.


Flowchart of a While Loop

C++ While and Do‑While Loops – Mastering Repetition in Your Code

Example 1: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1;

    // while loop from 1 to 5
    while (i <= 5) {
        cout << i << " ";
        ++i;
    }
    
    return 0;
}

Output

1 2 3 4 5

Below is a step‑by‑step breakdown of the program’s execution:

IterationVariablei <= 5Action
1sti = 1true1 printed, i becomes 2
2ndi = 2true2 printed, i becomes 3
3rdi = 3true3 printed, i becomes 4
4thi = 4true4 printed, i becomes 5
5thi = 5true5 printed, i becomes 6
6thi = 6falseLoop terminates

Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number;
    int sum = 0;

    // take input from the user
    cout << "Enter a number: ";
    cin >> number;

    while (number >= 0) {
        // add all positive numbers
        sum += number;

        // take input again if the number is positive
        cout << "Enter a number: ";
        cin >> number;
    }

    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Output

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

In this example, the program keeps asking the user for numbers. As long as the entered number is non‑negative, it is added to sum. A negative input signals the end of the loop, and the final sum is displayed.


C++ do…while Loop

The do…while loop differs from while by executing its body at least once before the condition is evaluated. This is useful when the loop’s body must run before the exit condition can be checked.

Its syntax is:

do {
    // body of loop
} while (condition);

Execution flow:


Flowchart of a do…while Loop

C++ While and Do‑While Loops – Mastering Repetition in Your Code

Example 3: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
    int i = 1;

    // do…while loop from 1 to 5
    do {
        cout << i << " ";
        ++i;
    } while (i <= 5);
    
    return 0;
}

Output

1 2 3 4 5

Execution steps:

IterationVariablei <= 5Action
Initiali = 1Not checked yet1 printed, i becomes 2
1sti = 2true2 printed, i becomes 3
2ndi = 3true3 printed, i becomes 4
3rdi = 4true4 printed, i becomes 5
4thi = 5true5 printed, i becomes 6
5thi = 6falseLoop terminates

Example 4: Sum of Positive Numbers Only

// program to find the sum of positive numbers
// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
    int number = 0;
    int sum = 0;

    do {
        sum += number;

        // take input from the user
        cout << "Enter a number: ";
        cin >> number;
    } while (number >= 0);
    
    // display the sum
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Output 1

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2

The sum is 25

Output 2

Enter a number: -6
The sum is 0.

When the first input is negative, the loop executes once and exits immediately, leaving sum unchanged.


Infinite Loops

An infinite loop occurs when the loop’s condition never evaluates to false. This can happen intentionally (e.g., a server that runs forever) or accidentally (logic errors).

// infinite while loop
while (true) {
    // body of the loop
}

Similarly, a do…while loop can be infinite:

int count = 1;

do {
    // body of loop
} while (count == 1);

Such loops consume resources until the program is terminated or the system runs out of memory.


for vs while Loops

The for loop is most suitable when the iteration count is known beforehand:

// loop iterated 5 times
for (int i = 1; i <= 5; ++i) {
    // body of the loop
}

In contrast, while and do…while loops are ideal when the number of iterations depends on runtime data, such as user input or the result of a complex condition.


Explore more C++ loop examples:


C Language

  1. Mastering C# While and Do‑While Loops: Syntax, Examples, and Best Practices
  2. Master C++ Conditional Statements: if, if...else, and Nested if...else Explained
  3. Master C++ For Loops: A Step-by-Step Guide
  4. Mastering C++ Continue Statement: Practical Examples & Loop Control
  5. Mastering While and Do‑While Loops in C: Practical Examples
  6. Mastering Python's While Loop: Syntax, Examples, and Best Practices
  7. Mastering Java While & Do‑While Loops: Step‑by‑Step Tutorial
  8. While vs. Do‑While Loops: Clear Comparison with Practical Examples
  9. Understanding C++ Loop Types: For, While, Do-While Explained
  10. Comprehensive Guide to Date and Time in C++