• Home
  • 5.2 do-while Loop

5.2 do-while Loop

View Categories

5.2 do-while Loop

1 min read

Table of Contents

A do-while loop repeatedly executes a block of statements while its controlling condition evaluates to true. Unlike a while loop, the condition is evaluated after the loop body, ensuring that the body executes at least once.

The do-while loop is useful when an operation must be performed before its continuation condition can be evaluated, such as displaying a menu or accepting user input.

Source Code #

#include <iostream>

int main()
{
    int count = 1;

    do
    {
        std::cout << "Count: " << count << '\n';
        ++count;
    }
    while (count <= 5);

    return 0;
}

Output #

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation #

  • do begins the loop body.
  • The statements inside the do block are executed before the condition is evaluated.
  • std::cout displays the current value of count.
  • ++count increments count by one after each iteration.
  • while (count <= 5) evaluates the loop condition after the loop body has executed.
  • If the condition evaluates to true, the loop body executes again.
  • If the condition evaluates to false, the loop terminates.
  • Because the condition is checked after the loop body, a do-while loop always executes its body at least once.
  • The semicolon after while (count <= 5); is required syntax for a do-while statement.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *