Do-While Loop in C: Executing Code with Post-Condition Control

“do-while” loop is a form of a loop in C that executes the code block first, followed by the condition. If the condition is true, the loop continues to run; else, it stops

 

Do While Loop in C

A do-while loop is another control flow statement in C that executes a block of code at least once, and then continues to repeat as long as a specified condition remains true. It’s similar to a while loop, but the condition is checked after the loop body is executed.

Syntax:

do {
    // Code to be executed
} while (condition);
  • Condition: An expression that is evaluated after each iteration. If the condition is true, the loop repeats. If it’s false, the loop terminates.

Example:

int i = 0;
do {
    printf("Hello, world!n");
    i++;
} while (i < 5);

In this example:

  • The loop body is executed at least once, even if the condition i < 5 is initially false.
  • The condition is checked after each iteration. If i is less than 5, the loop repeats.

Key Points:

  • The do-while loop guarantees at least one execution of the loop body.
  • The condition is checked after each iteration.
  • It’s useful when you want to execute a block of code at least once, regardless of the initial condition.

Example with a User-Defined Condition:

int number;

do {
    printf("Enter a positive number: ");
    scanf("%d", &number);
} while (number <= 0);

printf("You entered: %dn", number);

 

This example uses a do-while loop to prompt the user to enter a positive number until a valid input is provided. The loop will execute at least once, even if the user enters a negative number initially.

Comparison with while Loops:

  • Both while and do-while loops are used for iteration.
  • The main difference is that the do-while loop executes the loop body at least once before checking the condition.
  • Choose the appropriate loop type based on your specific requirements and the desired behavior.

Related Posts

Leave a Reply