C Do-While Loop

The do-while loop in C is used when you want to ensure that a block of code executes at least once before checking a condition. Unlike the while loop, the condition in a do-while loop is evaluated after the execution of the code block.

1. Do-While Loop Syntax

The do-while loop checks the condition after the loop's body has been executed. This guarantees that the code inside the loop will always run at least once.

Syntax:

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

Example:

                        
#include <stdio.h>
int main() 
{
    int i = 0;
    do {
         printf("%d\n", i);
         i++;
       } 
       while (i < 5);
    return 0;
}
                        
                    

Output:

0
1
2
3
4

2. Key Points of the Do-While Loop

3. When to Use the Do-While Loop

4. Comparison with Other Loops

Feature For Loop While Loop Do-While Loop
Condition Check At the beginning of each iteration At the beginning of each iteration At the end of each iteration
Minimum Iterations Zero or more Zero or more At least one
Use Case When the number of iterations is known When the number of iterations is unknown, condition checked before each iteration When the block must execute at least once, condition checked after each iteration