Nested Loops in C

 Nested loops is the feature in C that allows the looping of statements inside another loop





(toc)


Nested Loops in C

Nested loops are loops that are contained within other loops. They can be used to create complex patterns, iterate over multiple dimensions, or perform tasks that require multiple levels of iteration.


Basic Structure:


for (initialization1; condition1; increment1) {
    // Outer loop body
    for (initialization2; condition2; increment2) {
        // Inner loop body
    }
}

Example: Printing a Multiplication Table


#include <stdio.h>

int main() {
    int rows, cols;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);   

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

    return 0;
}

Explanation:

  • The outer loop iterates over the rows of the multiplication table.
  • The inner loop iterates over the columns of the multiplication table.
  • For each row and column, the product of the row and column numbers is calculated and printed.

Nested Loops in Other Loop Types:

Nested loops can be used with while and do-while loops as well. For example:


int i = 0;
while (i < 5) {
    int j = 0;
    while (j < 3) {
        // Inner loop body
        j++;
    }
    i++;
}

Key Points:

  • Nested loops are loops within loops.
  • They can be used to create complex patterns and perform tasks that require multiple levels of iteration.
  • The inner loop executes completely for each iteration of the outer loop.
  • Be careful with nested loops to avoid infinite loops or inefficient code.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!