C++ Do-While Loop


C++ Do-While Loop

In this tutorial, we will learn about the do-while loop in C++. We will cover the basics of using the do-while loop and provide examples to illustrate its usage.


What is a Do-While Loop

A do-while loop is a control flow statement that allows code to be executed repeatedly based on a condition. Unlike the while loop, the do-while loop guarantees that the code block will be executed at least once, as the condition is evaluated after the loop body.


Syntax

The syntax for the do-while loop in C++ is:

do {
    // Code block to be executed
} while (condition);

The do-while loop executes the code block once before checking the condition. If the condition is true, the loop repeats; otherwise, it exits.

Flowchart of Do-While Loop


Printing Numbers from 1 to 3

  1. Declare an integer variable i and initialize it to 1.
  2. Use a do-while loop to print numbers from 1 to 3.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int i = 1;
    do {
        cout << i << " ";
        i++;
    } while (i <= 3);
    return 0;
}

Output

1 2 3 


Repeating a Task Until User Enters a Specific Value

  1. Declare an integer variable num and a boolean variable repeat initialized to true.
  2. Use a do-while loop to repeat a task until the user enters a specific value (e.g., -1).
  3. Inside the loop, prompt the user to enter a number and read the input.
  4. Check if the input is equal to -1, and if so, set repeat to false to exit the loop.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int num;
    bool repeat = true;
    do {
        cout << "Enter a number (-1 to exit): ";
        cin >> num;
        if (num == -1) {
            repeat = false;
        }
    } while (repeat);
    return 0;
}

Output

User will be prompted to enter a number until they enter -1.


Calculating the Sum of Positive Numbers

  1. Declare an integer variable num and initialize it to 0, and another integer variable sum and initialize it to 0.
  2. Use a do-while loop to read positive numbers from the user and calculate their sum until a negative number is entered.
  3. Inside the loop, prompt the user to enter a number and read the input.
  4. If the input is positive, add it to sum.

C++ Program

#include <iostream>
using namespace std;
int main() {
    int num = 0, sum = 0;
    do {
        cout << "Enter a positive number (negative number to exit): ";
        cin >> num;
        if (num >= 0) {
            sum += num;
        }
    } while (num >= 0);
    cout << "Sum of positive numbers: " << sum;
    return 0;
}

Output

User will be prompted to enter positive numbers and the program will output the sum of those numbers.