C Do/While Loop
1. What is a do...while Loop?
-
The
do...whileloop executes the block of code first, then checks the condition. -
This guarantees that the loop body executes at least once, even if the condition is false.
Syntax:
Note the semicolon
;after thewhile(condition).
2. Simple Example
Output:
Loop executes the block first, then checks
i <= 5.
3. Difference Between while and do...while
| Feature | while Loop |
do...while Loop |
|---|---|---|
| Execution | Condition checked first | Code executed first |
| Minimum Iteration | 0 | 1 |
| Syntax | while(condition){...} |
do{...} while(condition); |
Example:
Output:
whileloop doesn’t execute because condition is false, butdo...whileexecutes once.
4. Using do...while for Input Validation
Sample Input/Output:
Loop keeps asking until a valid input is entered.
5. Key Points
-
Executes at least once, unlike
while. -
Condition is checked after the loop body.
-
Useful for input validation, menus, or tasks that must run at least once.
-
Remember the semicolon after
while(condition);.
