C While Loop Examples

C Tutorial

🔁 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

Featurewhilefor
Use caseUnknown iterationsKnown iterations
ConditionChecked firstChecked first
InitializationOutside loopInside 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)

  1. Difference between while and do-while

  2. When to use while loop?

  3. Can while loop be infinite?

  4. while(1) vs for(;;)

  5. Effect of break and continue in while


✅ Summary

while loop is condition-driven
✔ Best when iterations are unknown
✔ Used in menus, input validation, embedded loops
✔ Essential for logic building & interviews

You may also like...