How to Use Do While Loop in C: Syntax and Example
In C, a
do while loop executes the code block at least once and then repeats it while the condition is true. The syntax places the condition after the code block, ensuring the loop runs before checking the condition.Syntax
The do while loop syntax in C is:
do {
// code to execute
} while (condition);Explanation:
do: starts the loop block.- Code inside braces
{ }runs at least once. while (condition);: checks the condition after running the block.- If the condition is true, the loop repeats; if false, it stops.
c
do {
// statements
} while (condition);Example
This example prints numbers from 1 to 5 using a do while loop. It shows that the loop runs the code first, then checks the condition.
c
#include <stdio.h> int main() { int i = 1; do { printf("%d\n", i); i++; } while (i <= 5); return 0; }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes when using do while loops include:
- Forgetting the semicolon
;after thewhile(condition)line. - Using a condition that never becomes false, causing an infinite loop.
- Assuming the loop might not run at all (it always runs once).
Wrong example (missing semicolon):
c
do {
printf("Hello\n");
} while (0) // Missing semicolon here
// Correct version:
do {
printf("Hello\n");
} while (0);Quick Reference
Tips for using do while loops:
- Use when you want the loop to run at least once.
- Always end the
whilecondition with a semicolon. - Make sure the condition eventually becomes false to avoid infinite loops.
- Good for menus or input validation where you want to prompt first.
Key Takeaways
A do while loop runs the code block first, then checks the condition to repeat.
Always put a semicolon after the while(condition) line in a do while loop.
Use do while loops when you need the code to run at least once.
Avoid infinite loops by ensuring the condition will become false.
Common use cases include input prompts and menus that run before checking conditions.