Nearby lessons

44 of 124

C - While Loop

While Loop is one of the foundational topics in C programming. This lesson explains The while Loop with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The while Loop

Example01
CCode Cell
1while (condition) {
2 // body repeats while the condition is true
3}

The while Loop

The while loop checks the condition first, then runs the body. If the condition is false from the start, the body runs zero times.

In simple words: while is "check the door, then enter" — if the door is locked from the start, you never enter. The body may run zero times.
Example02
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i = 1;
6 while (i <= 5) {
7 printf("%d ", i);
8 i++; // important - otherwise the loop never ends
9 }
10}
Output

1 2 3 4 5 
      
📝 Key Takeaways
  • while checks first; do-while runs at least once; for gathers start/condition/update.
  • for is best when you know the number of iterations.
  • break stops the loop; continue skips one round.
  • Nested loops: inner loop completes for each outer round.
  • Pattern programs = outer loop (rows) + inner loop (columns).
  • Never forget the update (i++) — else you get an infinite loop.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2