C Nested Loops

A loop inside another loop is called a nested loop. For each round of the outer loop, the inner loop runs completely. Nested loops are used for tables, patterns and two dimensional data.

Multiplication table grid

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 5; j++) {
            printf("%4d", i * j);
        }
        printf("\n");
    }
    return 0;
}

Output:

Output of the above program is

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15

The outer loop picks the row (i). The inner loop prints the columns (j). After each row, printf("\n") moves to the next line.

Star pattern

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

Output:

Output of the above program is

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

Number pattern

#include <stdio.h>

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

Output:

Output of the above program is

1
1 2
1 2 3
1 2 3 4

Note: The total rounds are outer times inner. A loop of 1000 inside a loop of 1000 runs one million times, so be careful with big numbers.

Next: C break Statement.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.