Saturday, April 19, 2025

C++ Do While Loop

Do..While loop is interesting one. It's used when we need at least one operation executed.

It's easy to understand. Part of loop "do" will be first thing to type, than curly bracket with operations and jump, then closing curly bracket.

While part of loop will be OUTSIDE curly brackets.

Of course, starting point must be set first:

int counter = 1;

And do..while loop with simple operation of printing counter. After useful operation we have jump (counter = counter + 1). While part is outside:

do {
        cout << "Counter at the Moment: " << counter << endl;
        counter = counter + 1;
    } while (counter <= 20);

This is full working source:

#include <iostream>

using namespace std;

int main() {

    int counter = 1;

    do {
        cout << "Counter at the Moment: " << counter << endl;
        counter = counter + 1;
    } while (counter <= 20);

    return 0;

}

Result:

Counter at the Moment: 1
Counter at the Moment: 2
Counter at the Moment: 3
Counter at the Moment: 4
Counter at the Moment: 5
Counter at the Moment: 6
Counter at the Moment: 7
Counter at the Moment: 8
Counter at the Moment: 9
Counter at the Moment: 10
Counter at the Moment: 11
Counter at the Moment: 12
Counter at the Moment: 13
Counter at the Moment: 14
Counter at the Moment: 15
Counter at the Moment: 16
Counter at the Moment: 17
Counter at the Moment: 18
Counter at the Moment: 19
Counter at the Moment: 20

Process returned 0 (0x0)   execution time : 0.024 s
Press any key to continue.

Please note, if we use something big for counter, for example 12345, one operation will still work:

Counter at the Moment: 12345

Process returned 0 (0x0)   execution time : 0.089 s
Press any key to continue.

We will not use Do..While loop that much, but it's there if we need it.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...