Language: EN

cpp-bucle-while

What is and how to use the WHILE and DO-WHILE loops in C++

The while and do-while loops in C++ are control structures that allow repeating the execution of a block of code as long as a specific condition is met.

These loops are useful when the exact number of iterations is not known in advance and, instead, we want to repeat code under certain conditions.

Differences between While and Do-While

  • The while loop checks the condition before each iteration, while the do-while loop checks it after each iteration
  • The do-while loop guarantees at least one execution of the code block, whereas the while loop may not execute the block if the condition is false from the beginning

If you want to learn more about Loops
consult the Introduction to Programming Course read more

WHILE Loop

The while loop executes a block of code as long as a condition is true. The basic syntax of a while loop in C++ is as follows:

while (condition)
{
    // Code to execute while the condition is true
}
  • condition: It is an expression that is evaluated in each iteration. If it is true, the code block inside the while executes. If it is false, the loop ends.
  • Code to execute: This is where the code to be repeated is placed.

Basic Example

Let’s look at a basic example that uses a while loop to print numbers from 0 to 4:

#include <iostream>

int main() {
    int counter = 0;

    while (counter < 5) {
        std::cout << counter << std::endl;
        counter++;
    }

    return 0;
}

In this example:

  • The while loop prints the numbers from 0 to 4, as the condition counter < 5 is true while counter is less than 5.

DO-WHILE Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once. The basic syntax is as follows:

do
{
    // Code to execute at least once
} while (condition);
  • Code to execute: Executes at least once before the condition is checked.
  • Condition: Evaluated after each iteration. If it is true, the code block executes again; if it is false, the loop ends.

Basic Example

Let’s look at an example that uses a do-while loop to print numbers from 0 to 4:

#include <iostream>

int main() {
    int counter = 0;

    do {
        std::cout << counter << std::endl;
        counter++;
    } while (counter < 5);

    return 0;
}

In this example, the do-while loop

  • Produces the same result as the previous while loop
  • But guarantees that the code executes at least once, even if counter starts as 5

Practical Examples

These examples are intended to show how to use the While loop. This does not mean that it is the best way to solve the problems they address