๐ C Do-While Loop – Run First, Then Check
The do-while loop in C is like a while
loop, but with a twist โ it always runs the block at least once before checking the condition. Perfect for menus or input loops where you want something to happen first!
๐น Syntax of do-while loop
do { // code to execute } while (condition);
๐ Example: Count from 1 to 5
This program prints numbers from 1 to 5 using a do-while
loop.
#include <stdio.h> int main() { int i = 1; do { printf("Number: %d\n", i); i++; } while (i <= 5); return 0; }
๐ Example: Run at Least Once (Even if Condition is False)
This shows that the loop runs even when the condition is false from the start.
#include <stdio.h> int main() { int i = 10; do { printf("This runs at least once!\n"); } while (i < 5); return 0; }
๐ฏ Key Notes
- The block runs once before the condition is checked.
- Good for cases where you want to take input, display a menu, or run a message at least once.
- Always ends with a semicolon
;
after thewhile()
condition.
๐ Practice Time!
Try modifying the condition or combining it with user input. Build a fun loop that asks for a password until it's correct!