do-While

Home / C Programming / do-While

do-While


C programming, the `do-while` loop is another type of loop that allows you to repeatedly execute a block of code until a specified condition is no longer true. It's a post-test loop, meaning the condition is evaluated after each iteration.

The basic syntax of the `do-while` loop in C is as follows:

do {

    // code to execute

} while (condition);

The code block within the `do` statement is executed first, and then the condition is checked. If the condition is true, the loop continues to execute. If the condition is false, the loop is exited, and the program continues with the statement after the `do-while` loop.

Here's an example to illustrate the usage of `do-while` loop:

#include <stdio.h>

int main() {

    int count = 1;

    do {

        printf("Count: %d\n", count);

        count++;

    } while (count <= 5);

    printf("Loop complete.\n");

    return 0;

}

In this example, the program initializes a variable `count` with the value 1. The `do-while` loop executes the code block first, which prints the value of `count` and increments it by 1. Then, the condition `count <= 5` is evaluated. If the condition is true, the loop continues, and if the condition is false, the loop is exited. The output will be the numbers 1 to 5 printed on separate lines, similar to the previous example with the `while` loop.

One important difference between the `while` and `do-while` loops is that the `do-while` loop always executes the code block at least once, even if the condition is initially false. This guarantees that the code inside the loop will execute at least once before the condition is checked.

Here's an example that demonstrates this behavior:

#include <stdio.h>

int main() {

    int num = 10;

    do {

        printf("Number: %d\n", num);

        num++;

    } while (num < 5);

    printf("Loop complete.\n");

    return 0;

}

In this example, the condition `num < 5` is false initially because `num` is 10. However, the code block is still executed once, and "Number: 10" is printed. Then, the condition is checked, and since `num` is now 11, the loop is exited. The output will be "Number: 10" followed by "Loop complete."

It's important to ensure that the condition specified in the `do-while` loop will eventually become false to avoid infinite loops. Like the `while` loop, without a proper terminating condition or a mechanism to change the condition within the loop, it can lead to an infinite loop.