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
1
2
3
4
2. Key Points of the Do-While Loop
- The code inside the do block will execute at least once, even if the condition is false.
- The condition is checked after the execution of the loop's body, ensuring at least one iteration.
- If the condition is false after the first execution, the loop will terminate.
3. When to Use the Do-While Loop
- Use the do-while loop when you need the loop to run at least once, regardless of whether the condition is initially true or false.
- It is particularly useful when the loop's body contains code that must be executed before the condition is checked (e.g., input validation).
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 |