C While Loop Examples

🔁 C while Loop Examples (Beginner → Advanced)
The while loop in C language is used when the number of iterations is not known in advance.
It checks the condition first, then executes the loop body.
1️⃣ Basic while Loop (Print 1 to 5)
Output: 1 2 3 4 5
2️⃣ while Loop with User Input
✔ Loop depends on user input
3️⃣ Sum of Digits Using while ⭐
✔ Common interview problem
4️⃣ Reverse a Number Using while
5️⃣ Factorial Using while
6️⃣ while Loop with Array Traversal ⭐
✔ Used when size is dynamic
7️⃣ Infinite while Loop ⚠️
✔ Used in:
Embedded systems
Game loops
Servers
8️⃣ while Loop with break
Output: 1 2
9️⃣ while Loop with continue ⚠️
Output: 1 2 4 5
📌 Increment before continue to avoid infinite loop
🔟 Menu-Driven Program Using while ⭐
✔ Very common in real programs
1️⃣1️⃣ while vs for Loop
| Feature | while | for |
|---|---|---|
| Use case | Unknown iterations | Known iterations |
| Condition | Checked first | Checked first |
| Initialization | Outside loop | Inside loop |
1️⃣2️⃣ Common Mistakes ❌
❌ Forgetting to update loop variable
❌ Infinite loop due to wrong condition
❌ Misusing continue
❌ Not initializing variable
📌 Interview Questions (Must Prepare)
Difference between
whileanddo-whileWhen to use
whileloop?Can
whileloop be infinite?while(1)vsfor(;;)Effect of
breakandcontinueinwhile
✅ Summary
✔ while loop is condition-driven
✔ Best when iterations are unknown
✔ Used in menus, input validation, embedded loops
✔ Essential for logic building & interviews
