Nested Loops in C

Nested Loops in C


Introduction

In C programming, sometimes we need to repeat a loop inside another loop.
This is called a nested loop.

👉 Nested loops are very useful for solving problems like patterns, matrices, and complex iterations.


What is a Nested Loop?

A nested loop is:
👉 A loop inside another loop

  • Outer loop → controls overall iterations
  • Inner loop → runs completely for each outer loop cycle

Basic Syntax

for (initialization; condition; increment) {

for (initialization; condition; increment) {
// inner loop code
}

}

How Nested Loop Works

👉 Example flow:

  • Outer loop runs 1 time
  • Inner loop runs fully
  • Then outer loop repeats

Example 1: Simple Nested Loop

#include <stdio.h>

int main() {
int i, j;

for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
printf("i = %d, j = %d\n", i, j);
}
}

return 0;
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

Example 2: Star Pattern

#include <stdio.h>

int main() {
int i, j;

for (i = 1; i <= 4; i++) {
for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

return 0;
}

Output

*
* *
* * *
* * * *

Example 3: Multiplication Table

#include <stdio.h>

int main() {
int i, j;

for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
printf("%d ", i * j);
}
printf("\n");
}

return 0;
}

Output

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Types of Nested Loops

  • Nested for loops
  • Nested while loops
  • Mixed loops (for inside while, etc.)

Real-World Uses

  • Pattern printing
  • Matrix operations
  • Game development logic
  • Data processing

Common Mistakes

  • ❌ Wrong loop condition
  • ❌ Incorrect nesting
  • ❌ Infinite loops
  • ❌ Forgetting printf("\n")

Pro Tips

  • ✔ Always understand loop flow
  • ✔ Practice pattern programs
  • ✔ Use meaningful variables
  • ✔ Avoid too many nested levels

Conclusion

Nested loops are powerful tools in C programming. They allow you to handle complex problems like patterns and matrices efficiently.

Mastering nested loops will greatly improve your coding skills.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C