0
0
C++programming~5 mins

Do–while loop in C++

Choose your learning style9 modes available
Introduction

A do-while loop lets you run a block of code at least once, then repeat it while a condition is true.

When you want to ask a user for input and repeat until they give a valid answer.
When you need to run a menu at least once and keep showing it until the user chooses to exit.
When you want to perform an action first, then check if it should continue.
When you want to repeat a task but must do it at least once no matter what.
Syntax
C++
do {
    // code to run
} while (condition);

The code inside do { } runs first, then the condition is checked.

If the condition is true, the loop repeats. If false, it stops.

Examples
This prints numbers 1 to 3 using a do-while loop.
C++
int i = 1;
do {
    std::cout << i << " ";
    i++;
} while (i <= 3);
This asks the user if they want to continue and repeats if they type 'y'.
C++
char answer;
do {
    std::cout << "Continue? (y/n): ";
    std::cin >> answer;
} while (answer == 'y');
Sample Program

This program prints "Count is: " followed by numbers 1 to 5 using a do-while loop.

C++
#include <iostream>

int main() {
    int count = 1;
    do {
        std::cout << "Count is: " << count << "\n";
        count++;
    } while (count <= 5);
    return 0;
}
OutputSuccess
Important Notes

Remember the semicolon ; after the while(condition) line is required.

Unlike a while loop, a do-while loop always runs the code block at least once.

Summary

A do-while loop runs code first, then checks the condition.

It repeats the code while the condition is true.

Use it when you want the code to run at least once before checking.