C Programs Tutorials | IT Developer
IT Developer

C Programming - C nested Loops



Share with a Friend

C Programming - C nested Loops

Nested Loops in C

A nested loop is a loop inside another loop. In C, you can place a loop inside another loop to perform repeated operations on data in multiple dimensions or to solve complex problems that require iterating through several levels of data.

Types of Nested Loops:

  • Nested for Loops
  • Nested while Loops
  • Nested do-while Loops
  • Combination of Different Types of Loops (e.g., for inside while or vice versa)

Syntax of Nested Loops:

C

for (initialization; condition; update) {

    // Outer loop body

    for (initialization; condition; update) {

        // Inner loop body

    }

    // Continue with outer loop body

}

  • The outer loop runs a set number of times.
  • For each iteration of the outer loop, the inner loop will execute its set number of iterations.
  • You can nest as many loops as needed.

Example 1: Nested for Loop

Let’s look at a simple example where we print a multiplication table using nested for loops:

C

#include <stdio.h>

int main() {

    // Nested for loop to print a multiplication table from 1 to 5

    for (int i = 1; i <= 5; i++) {

        for (int j = 1; j <= 5; j++) {

            printf("%d\t", i * j);  // Multiply i and j

        }

        printf("\n");  // Move to the next line after each row

    }

    return 0;

}

Explanation:

  • The outer loop (with i) runs 5 times (from 1 to 5).
  • For each iteration of the outer loop, the inner loop (with j) also runs 5 times (from 1 to 5), printing the product of i and j.
  • After the inner loop completes for a particular i, a newline is printed to separate the rows of the table.

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     

Example 2: Nested while Loop

Here’s an example using nested while loops to print a right-angle triangle pattern:

C

#include <stdio.h>

int main() {

    int i = 1;

    // Outer while loop

    while (i <= 5) {

        int j = 1;

        // Inner while loop

        while (j <= i) {

            printf("* ");  // Print stars

            j++;  // Increment inner loop counter

        }

        printf("\n");  // Move to the next line

        i++;  // Increment outer loop counter

    }

    return 0;

}

Explanation:

  • The outer while loop runs 5 times (i from 1 to 5).
  • The inner while loop prints stars, and the number of stars printed corresponds to the value of i.
  • After each iteration of the inner loop, a newline is printed to create the right-angle triangle shape.

Output:

*

* *

* * *

* * * *

* * * * *

Example 3: Nested do-while Loop

Here’s an example using nested do-while loops to print the same right-angle triangle pattern:

C

#include <stdio.h>

int main() {

    int i = 1;

    // Outer do-while loop

    do {

        int j = 1;

        // Inner do-while loop

        do {

            printf("* ");  // Print stars

            j++;  // Increment inner loop counter

        } while (j <= i);

        printf("\n");  // Move to the next line

        i++;  // Increment outer loop counter

    } while (i <= 5);

    return 0;

}

Explanation:

  • The outer do-while loop runs 5 times (i from 1 to 5).
  • The inner do-while loop prints stars, and the number of stars printed corresponds to the value of i.
  • After each iteration of the inner loop, a newline is printed to create the right-angle triangle shape.

Output:

*

* *

* * *

* * * *

* * * * *

Example 4: Mixed Nested Loops

You can also mix different types of loops inside each other. For example, here’s a combination of a for loop inside a while loop:

C

#include <stdio.h>

int main() {

    int i = 1;

    // Outer while loop

    while (i <= 3) {

        // Inner for loop

        for (int j = 1; j <= 4; j++) {

            printf("%d ", i * j);  // Print product of i and j

        }

        printf("\n");

        i++;  // Increment outer loop counter

    }

    return 0;

}

Explanation:

  • The outer while loop runs 3 times.
  • For each iteration of the outer loop, the inner for loop runs 4 times and prints the product of i and j.

Output:

1 2 3 4

2 4 6 8

3 6 9 12

Performance Considerations for Nested Loops:

  • Nested loops can lead to significant performance issues if the number of iterations grows quickly. For example, if you have a nested loop with both loops running a large number of times, the total number of iterations can be the product of the iteration counts, making the program slow.
  • Time Complexity: The time complexity of nested loops depends on how many times each loop runs. For example:
    • A nested for loop where both loops run n times will have a time complexity of O(n²).
    • A nested for loop with the outer loop running n times and the inner loop running m times will have a time complexity of O(n * m).

Summary of Nested Loops in C:

  • Nested loops are useful when you need to process multi-dimensional data or perform repeated operations within other repeated operations.
  • You can nest different types of loops (for, while, do-while), and the inner loop executes completely for each iteration of the outer loop.
  • Nested loops are efficient when used appropriately, but excessive nesting can lead to inefficient algorithms, especially when the number of iterations grows large.