C Nested Loops

1. What is a Nested Loop?

  • A nested loop is a loop inside another loop.

  • The inner loop completes all its iterations for each iteration of the outer loop.

  • Syntax:

for (initialization1; condition1; increment1) { // Outer loop
for (initialization2; condition2; increment2) { // Inner loop
// code to execute repeatedly
}
}

Nested loops can also be while inside for, for inside while, or while inside while.


2. Simple Nested for Loop Example

Print a 5×5 multiplication table (partial):

#include <stdio.h>

int main() {
int i, j;

for (i = 1; i <= 5; i++) { // outer loop
for (j = 1; j <= 5; j++) { // inner loop
printf("%d\t", 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

3. Printing Patterns

Right-Angle Triangle of *

#include <stdio.h>

int main() {
int i, j;

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

return 0;
}

Output:

*
* *
* * *
* * * *
* * * * *

Square Pattern of Numbers

#include <stdio.h>

int main() {
int i, j;

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

return 0;
}

Output:

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

4. Key Points About Nested Loops

  1. Inner loop runs completely for every iteration of the outer loop.

  2. Useful for patterns, matrices, tables, and multi-dimensional arrays.

  3. Be careful: too many nested loops can slow down the program (time complexity increases).

  4. Can mix different types of loops (for, while, do...while) inside each other.


5. Example – Multiplication Table Using Nested Loops

#include <stdio.h>

int main() {
int i, j;

printf("Multiplication Table 1 to 3:\n");

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

return 0;
}

Output:

1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *