DO-WHILE LOOP:


The do-while loop operates similarly to the while loop,with the key distinction being that in a do-while loop, the statement executes at least once, even if the specified condition is false. The do-while loop executes the statement first, followed by the condition check. If the condition is true, the statement executes again; otherwise, the program ends.

The syntax of the do-while loop is as follows:

do 
{ 
  // Code block containing one or more C++ statements.
} 
while ( condition );

The condition is evaluated at the end of the loop body instead of at the beginning. Consequently, the body of the loop executes at least once before the condition is assessed. If the condition is true, the loop returns to the beginning of the block and executes it again.

Essentially, a do-while loop is a while loop in reverse. While a while loop states:

  • Loop while the condition is true and execute this block of code,

A do-while loop says:

  • Execute this block of code, then loop back while the condition is true.

To better grasp how the do-while loop operates, let's consider a simple example of a guessing game. In this scenario, a number is hidden, and the player must guess the correct number. This loop continues until the player guesses correctly.

EXAMPLE 1 - CPP Copy to Clipboard  
#include <iostream>
using namespace std;

int main() {
    int number = 55; // The number to be guessed
    int guess; // Variable to store the user's guess
    
    cout << "Guess the number: ";
    cin >> guess;

    // Loop until the guess matches the number
    do {
        cout << "Wrong guess...!!" << endl;
        cout << "\nGuess again: ";
        cin >> guess;
    } while (guess != number);

    cout << "Congratulations! That's the right guess." << endl;
    return 0;
}

Here's another practical example demonstrating the significance of the do-while loop. We'll create a simple calculator that continuously prompts the user to enter numbers until they input zero. Upon termination, the calculator displays the sum of all entered numbers.

EXAMPLE 2 - CPP Copy to Clipboard  
#include <iostream>
using namespace std;

int main() {
    int number = 0; // Variable to store user input
    int sum = 0; // Variable to store the sum of all entered numbers

    // Loop continues until the user enters zero
    do {
        cout << "Please enter a number to add: ";
        cin >> number;
        sum += number; // Add entered numbers to the sum
    } while (number != 0);

    // Display the sum of all entered numbers
    cout << "\n\nThe sum of all entered numbers is: " << sum;

    return 0;
}

These examples illustrate how to use the do-while loop effectively in C++ programming.