Do-While loops

Do-While Loop Statement in Computer Programming

The do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of each iteration. Unlike the while loop, which tests the loop condition before the block of code runs, the do-while loop checks its condition after the code has executed. This ensures that the block of code inside the loop executes at least one time.

Syntax:

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

Example in C#:

using System;

class Program {
    static void Main() {
        int counter = 0;
        do {
            Console.WriteLine(counter);
            counter++;
        } while (counter < 5);
    }
}

Note: Python does not have a built-in do-while loop construct. Instead, a similar effect can be achieved using a while loop. Here is an equivalent approach in Python:

Example in Python:

counter = 0
while True:
    print(counter)
    counter += 1
    if counter >= 5:
        break

Last updated

Was this helpful?