C++ Do/While Loop

Do/While Loop in C++

#include <iostream>
using namespace std;

int main() {
    int count = 1;

    do {
        cout << "Count is: " << count << endl;
        count++;
    } while (count <= 5);

    return 0;
}

Explanation:

  • #include : This line includes the input/output stream library in the program.

  • using namespace std;: This line allows the program to use entities such as cout without specifying the namespace.

  • int main(): This is the main function where the program execution begins.

  • int count = 1;: This declares and initializes an integer variable "count" with the value 1.

  • do { ... } while (count <= 5);: This is a do-while loop that first executes the code block inside the "do" part, then checks the condition in the "while" part. The loop continues to execute as long as the condition (count <= 5) is true.

  • cout << "Count is: " << count << endl;: This line outputs the current value of "count" along with the text "Count is: " to the console.

  • count++;: This statement increments the value of "count" by 1 in each iteration of the loop.

  • return 0;: This statement indicates that the program has executed successfully and returns 0 to the operating system.