Do/While Loop in C
The do...while loop is similar to the while loop but guarantees that the loop body executes at least once. The condition is evaluated after the loop body is executed.
Syntax of Do/While Loop
do {
// Code to execute
} while (condition);
Example: User Input Validation
#include <stdio.h>
int main() {
int number;
do {
printf("Enter a positive number: ");
scanf("%d", &number);
} while (number <= 0);
printf("You entered: %d\n", number);
return 0;
}
Code Explanation: The loop prompts the user to enter a positive number. If the user enters a non-positive number, the loop repeats.
Best Practices
- Use
do...whilewhen the loop body must execute at least once. - Ensure that the loop condition will eventually become false.
- Use clear and concise conditions for readability.
Don'ts
;) after the while condition.do...while when the loop might not need to execute at all.Key Takeaways
- The
do...whileloop ensures the loop body runs at least once. - Useful for scenarios like input validation where an action must occur before checking a condition.
- Always remember the semicolon after the
whilecondition.