C While Loop

C Tutorial

 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 while loop repeatedly executes a block of code as long as a given condition remains true.


 Syntax of while Loop

Execution Flow

  1. Check condition

  2. If true → execute loop body

  3. Update loop variable

  4. Go back to step 1


 Simple while Loop Example

Print numbers from 1 to 5


 

Output

1 2 3 4 5

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

1 2

while Loop with continue

Output

1 2 4 5
  •  Always update loop variable before continue to avoid infinite loop

while vs for Loop

Featurewhilefor
Best used whenIterations unknownIterations known
InitializationOutside loopInside loop
ReadabilityMediumHigh

Common Mistakes

  •  Forgetting to update loop variable
  • Infinite loop due to wrong condition
  •  Using = instead of ==
  • Misusing continue

 Interview Questions (Must Prepare)

  1. When should we use a while loop?

  2. Difference between while and do-while

  3. Can a while loop be infinite?

  4. What happens if condition is false initially?

  5. Role of break and continue in while


 Summary

  • while loop checks condition first
  •  Best when number of iterations is unknown
  •  Widely used in menus, validation, embedded systems
  •  Essential for logic building & interviews

You may also like...