#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Loops

Nested Loops in C

What are Nested Loops?

A nested loop is a loop placed inside the body of another loop. The inner loop completes all of its iterations for each single iteration of the outer loop.

Example: Printing a Pattern

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        printf("*");
    }
    printf("\n");
}
// Output:
// *
// **
// ***

Common Uses

Nested loops are widely used for working with 2D arrays/matrices, printing patterns, and algorithms like bubble sort.

A Complete Pattern Program

This program prints a right-angled triangle of stars. The outer loop controls the rows and the inner loop controls how many stars appear in each row.

#include <stdio.h>

int main(void) {
    int rows = 4;
    for (int i = 1; i <= rows; i++) {        /* outer loop: one pass per row */
        for (int j = 1; j <= i; j++) {       /* inner loop: i stars in row i */
            printf("* ");
        }
        printf("\n");                         /* move to the next line */
    }
    return 0;
}

Output:

*
* *
* * *
* * * *

Tracing How Many Times the Inner Loop Runs

When i is 1, the inner loop runs once. When i is 2, it runs twice, and so on. For 4 rows that is 1 + 2 + 3 + 4 = 10 inner iterations in total. In general, the triangle pattern runs n(n + 1) / 2 times, while a rectangle pattern where the inner loop always runs n times runs n × n times.

This is why nested loops matter for performance. With 1,000 items, a pair of full nested loops performs a million inner iterations. Many sorting and searching improvements are really about replacing a nested loop with something smarter.

Working With a 2D Array

Matrices are the most common real use. The outer loop walks the rows and the inner loop walks the columns of each row:

int marks[3][4] = {
    {70, 82, 64, 90},
    {55, 61, 73, 68},
    {88, 79, 92, 85}
};

for (int r = 0; r < 3; r++) {
    int total = 0;
    for (int c = 0; c < 4; c++) {
        total += marks[r][c];
    }
    printf("Student %d total: %d\n", r + 1, total);
}

Notice that total is reset inside the outer loop. Declaring it outside both loops would keep adding every student's marks together.

Controlling the Flow: break and continue

A break inside the inner loop only exits the inner loop; the outer loop carries on with its next iteration. To stop both loops, for example once a search finds its target, use a flag variable:

int found = 0;
for (int r = 0; r < 3 && !found; r++) {
    for (int c = 0; c < 4; c++) {
        if (marks[r][c] == 92) {
            printf("Found at row %d, column %d\n", r, c);
            found = 1;
            break;
        }
    }
}

Similarly, continue skips only the rest of the current inner iteration and moves straight to the next value of the inner counter. Use it to skip cells you do not care about, such as the diagonal of a matrix, without wrapping the whole inner body in an extra if block.

When you find yourself needing a flag to escape several levels, consider moving the nested loops into their own function and using return as soon as the answer is found. The code usually becomes shorter and easier to read.

Frequent Mistakes

  • Reusing the same counter name for both loops, such as i twice. The inner loop then changes the outer loop's counter and the program loops wrongly or forever.
  • Off-by-one bounds with arrays. A 3 by 4 array uses indexes 0 to 2 and 0 to 3, so write r < 3, not r <= 3.
  • Swapped row and column limits, which reads past the end of each row.
  • Doing heavy work in the inner loop that could be done once in the outer loop, such as a calculation that only depends on the row.

Ready to master real-world C Programming development?

Learn C Programming hands-on with mentor-led, live sessions.

Explore Course