Nested for looping

If we have a for loop inside another loop, it is known as a nested for loop.

In simple words Java allows the nesting of loops, when we put a loop within another loop we call it a nested loop. Nested loops are extremely useful when we need to iterate through a matrix array or perform any pattern-based question

nested loop has one loop inside of another. When working in two dimensions, they are usually used to print stars in rows and columns, as the example below illustrates. An inner loop that is nested inside an outer loop repeats itself numerous times. Every time the outer loop iterates, the inner loop will begin anew. Before the outer loop may move on to the following iteration, the inner loop must complete all of its iterations.

How it works:

  1. The program execution gets started from the outer for loop. Outer for loop variable is initialized and the provided condition is checked. If the condition of the outer for loop is satisfied (the outer for loop condition is true) then, we come inside the outer for loop body.
  2. Now, the control of the execution is transferred to the inner for loop, and the inner loop variable is initialized
  3. After the initialization, the inner for loop condition is checked. Similar to the outer for loop, if the condition is true then we move inside the inner for loop body.
  4. When the inner for loop’s body is run, the counter is incremented or decremented in accordance with the code.
  5. The inner for loop body will be executed twice when the condition is checked once more.

Example of Nested for loop:

public class NestedForExample {  
        public static void main(String[] args) {
        // loop of i
        for(int i = 1; i <= 3; i++) {
            // loop of j
            for (int j = 1; j <= 2; j++) {
                System.out.println(i + " " + j);

            } 
        } 
        }
}

Output:

1 1
1 2
2 1
2 2
3 1
3 2

Explanation:

  1. public class Nested For Example {: This line begins the definition of a public Java class named “Nested For Example.”
  2. public static void main(String[] args) {: This is the entry point of the program. It’s the main method where the program execution starts.
  3. for (int i = 1; i <= 3; i++) {: This is the outer loop, represented by the variable i, which starts with an initial value of 1 and keeps on as long as i is equal to or less than 3. After each iteration, the value of i is incremented by 1 (i++).
  4. for (int j = 1; j <= 2; j++) {: This is the inner loop, represented by the variable j, which starts with an initial value of 1 and keeps on as long as i is equal to or less than 2. After each iteration, the value of j is incremented by 1 (j++).
  5. System.out.println(i + ” ” + j);: This line prints the current values of i and j separated by a space, followed by a new line. The output will be in the format of “i j” where i is the current value of the outer loop and j is the current value of the inner loop.
  6. The inner loop (for (int j = 1; j <= 2; j++) { … }) will run twice for each iteration of the outer loop. So, for each value of i (1, 2, and 3), the inner loop will execute twice with j being 1 and 2, respectively.
  7. After the inner loop completes all its iterations for the current value of i, the outer loop (for (int i = 1; i <= 3; i++) { … }) will continue to the next value of i until it reaches 3, which is the termination condition for the outer loop.

Another Example of Nested for loop

public class PyramidExample {
     public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <=
    i; j++) {
                System.out.print("* ");
            }
            System.out.println();// new line
        }

     }
}

Output:

*

* *

* * *

* * * *

* * * * *

Explanation:

  1. We define a public class named PyramidExample. In Java, each program must have a main class, and in this case, the main class is called PyramidExample.
  2. The main method is the entry point of the Java program, and it is where the program execution starts. It is declared as public static void main(String[] args).
  3. Inside the main method, we have a nested loop structure to create the pyramid pattern. The outer loop is responsible for controlling the number of rows in the pyramid. It is defined as for (int i = 1; i <= 5; i++), which means it will loop from i = 1 to i = 5 (both inclusive). The variable i represents the current row number.
  4. Inside the outer loop, we have another nested loop (inner loop) that controls the number of asterisks to be printed in each row. It is defined as for (int j = 1; j <= i; j++), where j represents the number of asterisks to be printed in the current row (i).
  5. In the inner loop, System.out.print(“* “) is used to print an asterisk followed by a space (e.g., “* “). This will print i number of asterisks in each row as controlled by the inner loop.
  6. After the inner loop has printed all the asterisks in the current row, System.out.println() is used to move to the next line, creating a new line for the next row of the pyramid.
  7. The outer loop continues to the next iteration, and the inner loop prints the corresponding number of asterisks for that row, and so on until all rows of the pyramid are printed.

The output is a pyramid pattern with 5 rows, where each row contains the corresponding number of asterisks. The first row has 1 asterisk, the second row has 2 asterisks, the third row has 3 asterisks, and so on.

 

 

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close