C While Loop

C while Loop (Complete Tutorial: Beginner → Advanced)
The while loop in C language is used when the number of iterations is not known beforehand.
It checks the condition first, and only if it’s true does the loop body execute.
What is a while Loop?
A
whileloop repeatedly executes a block of code as long as a given condition remains true.
Syntax of while Loop
Execution Flow
Check condition
If true → execute loop body
Update loop variable
Go back to step 1
Simple while Loop Example
Print numbers from 1 to 5
Output
while Loop with User Input
- Loop depends on user input
- Very common in real programs
Sum of Digits Using while (Interview Favorite)
Reverse a Number Using while
while Loop with Arrays
- Used when size is dynamic or unknown
Infinite while Loop
Used in:
Embedded systems
Servers
Game loops
Must use break to exit
while Loop with break
Output
while Loop with continue
Output
- Always update loop variable before
continueto avoid infinite loop
while vs for Loop
| Feature | while | for |
|---|---|---|
| Best used when | Iterations unknown | Iterations known |
| Initialization | Outside loop | Inside loop |
| Readability | Medium | High |
Common Mistakes
- Forgetting to update loop variable
- Infinite loop due to wrong condition
- Using
=instead of== Misusingcontinue
Interview Questions (Must Prepare)
When should we use a
whileloop?Difference between
whileanddo-whileCan a
whileloop be infinite?What happens if condition is false initially?
Role of
breakandcontinueinwhile
Summary
whileloop checks condition first- Best when number of iterations is unknown
- Widely used in menus, validation, embedded systems
- Essential for logic building & interviews
