
Here’s how it works:
do { // code to be executed } while (condition);
#include <stdio.h> int main() { int i = 1; do { printf("i = %d\n", i); i++; } while (i <= 5); return 0; }
This program will print the numbers 1 to 5 using the do-while loop. Here’s how the loop works:
When you run this program, you should see the following output:
i = 1
i = 2
i = 3
i = 4
i = 5
A do-while loop in C is a type of loop statement that executes a block of code repeatedly until a specified condition is met.the do-while loop will always execute the code block at least once, regardless of whether the condition is true or false.
do {
/* code block to be executed */
} while (condition);
while
loop might not execute the block of code at all if the condition is initially false, whereas a do-while
loop will always execute the block of code at least once before checking the condition.while
loop evaluates the condition before executing the block of code, while the do-while
loop evaluates the condition after executing the block of code.break command (C and C++)
To end a do-while
loop in C, the condition within the loop must evaluate to false ,or using a break statement to exit the loop
The do-while
loop in C is a useful construct for repetitive execution of a block of code. Here are some common use cases for the do-while
loop:
Yes, it is possible to have nested do-while
loops in C. This means that a do-while
loop can be placed inside another do-while
loop, or inside any other type of loop. Nested loops are often used to process two-dimensional arrays or to traverse complex data structures.