Nearby lessons

49 of 124

C - Nested Loops

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

Nested Loops

A loop inside a loop is a nested loop. For each round of the outer loop, the inner loop runs completely. Nested loops build patterns:

Trainer's Note: The secret of pattern programs: outer loop = number of rows, inner loop = what is printed in each row. Change the inner condition and you change the whole pattern.
Example01
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int i, j;
6 for (i = 1; i <= 3; i++) { // outer loop - rows
7 for (j = 1; j <= i; j++) { // inner loop - stars in a row
8 printf("* ");
9 }
10 printf("\n");
11 }
12}
Output

* 
* * 
* * * 
      
📝 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

1 Questions
Progress: 0 / 1