๐ C While Loop – Repeat Until a Condition Fails
The while loop in C runs a block of code as long as a specified condition is true. It’s great when you don’t know how many times the loop should run โ just give it a condition and let it roll!
๐น Syntax of while loop
while (condition) { // code to execute }
๐ Example: Count from 1 to 5
This program prints numbers from 1 to 5 using a while
loop.
#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("Number: %d\n", i); i++; } return 0; }
๐ Example: Print Even Numbers
This version prints odd numbers from 1 to 9
#include <stdio.h> int main() { int i = 1; while (i <= 9) { if (i % 2 != 0) { printf("%d\n", i); } i++; } return 0; }
๐ฏ Key Notes
- The loop checks the condition before running the block.
- If the condition is false on the first check, the loop won’t run at all.
- Great for loops that depend on dynamic values like user input.
๐ Practice Time!
Try modifying the condition to count down, accept specific input ranges, or create a simple menu loop!