Nested while loop in C

Nested While Loop in C. Nested While Loop in C Tutorial. Learn Nested While Loop in C
Nested While Loop in C

What is nested while loop in C?

A nested while loop is a loop inside another loop. This means that the outer loop runs multiple times, and for each iteration of the outer loop, the inner loop also runs multiple times.

Nested while loops are useful when you need to perform a task multiple times, and that task requires another set of actions to be performed multiple times as well.

Syntax:

while (condition1) {
  while (condition2) {
    // code to be executed
  }
}

Here, condition1 is the condition for the outer loop, and condition2 is the condition for the inner loop. The code inside the inner loop will execute repeatedly as long as condition2 is true, and the inner loop will repeat for each iteration of the outer loop as long as condition1 is true.

Examples of nested while loops:

1. Printing a Pyramid Pattern of Asterisk

#include <stdio.h>
int main() {
    int i = 0, j = 0, n = 5;
    while (i < n) {
        while (j < n-i) {
            printf("* ");
            j++;
        }
        printf("\n");
        j = 0;
        i++;
    }
    return 0;
}

Output:

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

Explanation:

This code prints a pyramid pattern of asterisks with decreasing size. The outer while loop runs from i = 0 to n-1, and the inner while loop runs from j = 0 to n-i-1. The number of asterisks printed in each row decreases as we move down the pyramid. The variable i keeps track of the current row number, and the variable j keeps track of the number of asterisks printed in that row.

2. Printing a Box Pattern of Asterisk

#include <stdio.h>
int main() {
    int i = 1, j = 1, n = 10;
    while (i <= n) {
        while (j <= n) {
            if (i == 1 || i == n || j == 1 || j == n)
                printf("*");
            else
                printf(" ");
            j++;
        }
        printf("\n");
        j = 1;
        i++;
    }
    return 0;
}

Output:

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

Explanation:

This code prints a box pattern of asterisks with a hollow center. The outer while loop runs from i = 1 to n, and the inner while loop runs from j = 1 to n. The condition inside the inner loop checks whether the current position is on the boundary of the box, in which case we print an asterisk, or inside the box, in which case we print a space.

3. Printing a Pyramid of Increasing Numbers

#include <stdio.h>
int main() {
    int i = 0, j = 0, k = 1, n = 5;
    while (i < n) {
        while (j <= i) {
            printf("%d ", k);
            j++;
            k++;
        }
        printf("\n");
        j = 0;
        i++;
    }
    return 0;
}

Output:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Explanation:

This code prints a pattern of increasing numbers in a triangle shape. The outer while loop runs from i = 0 to n-1, and the inner while loop runs from j = 0 to i. The variable k keeps track of the current number to be printed, and is incremented after each number is printed. The number of numbers printed in each row increases as we move down the triangle.

4. Printing Multiplication Table from 1 to 10

#include <stdio.h>

int main() {
    int num, i, j;
    i = 1;
    while(i <= 10) {
        j = 1;
        while(j <= 10) {
            printf("%d x %d = %d\n", i, j, i*j);
            j++;
        }
        i++;
        printf("\n");
    }
    
    return 0;
}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
...
...
...
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Explanation:

In above example, the program display a multiplication table for that number from 1 to 10. The outer while loop iterates from 1 to 10 and the inner while loop iterates from 1 to 10 for each value of i, displaying the result of the multiplication for each pair of numbers. Once the inner loop has completed iterating for a value of i, the program prints a new line to create a separation between the rows of the multiplication table.

5. Matrix Multiplication

#include <stdio.h>

#define ROWS 3
#define COLUMNS 3

int main() {
    int a[ROWS][COLUMNS] = { {1, 2, 3},
                             {4, 5, 6},
                             {7, 8, 9} };
    int b[ROWS][COLUMNS] = { {9, 8, 7},
                             {6, 5, 4},
                             {3, 2, 1} };
    int c[ROWS][COLUMNS] = { {0, 0, 0},
                             {0, 0, 0},
                             {0, 0, 0} };

    int i = 0, j = 0, k = 0;

    while (i < ROWS) {
        while (j < COLUMNS) {
            while (k < COLUMNS) {
                c[i][j] += a[i][k] * b[k][j];
                k++;
            }
            k = 0;
            j++;
        }
        j = 0;
        i++;
    }

    printf("Result:\n");
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLUMNS; j++) {
            printf("%d ", c[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Result:
30  24  18  
84  69  54  
138 114  90  

Explanation:

This code uses nested while loops to multiply two matrices a and b and store the result in matrix c. The outer while loop iterates over the rows of a and c, the middle while loop iterates over the columns of b and c, and the innermost while loop calculates the dot product of a row of a and a column of b to fill in a single element of c.

Rules to follow when using nested while loop in C:

  1. Make sure that the loops have a proper termination condition to avoid infinite looping.
  2. Avoid using too many nested loops, as it can make the code complex and difficult to read.
  3. Use meaningful variable names to make the code easier to understand.
  4. Ensure that the variables used in the outer loop and inner loop do not have the same name to prevent confusion.
  5. Avoid using nested loops for small tasks that can be accomplished with a single loop.

More: