Nested Loop
- Eclipse: Oxygen
- Java: 1.8
A nested loop is a loop within a loop, an inner loop within the body of an outer one. In this tutorial, we will learn the syntax for nested loop and understand the examples.
Program
In the following statement for loop is inside the body of another for a loop.
In this program, the inner loop and the outer loop are initialized to 1. The outer loop’s condition is  i <= 3 whereas for inner loop is j <= 3. Here outer loop iterates 3 times and for each iteration of the outer loop, the inner loop executes three times.
1 2 3 4 5 6 7 8 9 |
public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("value of i:" + i + " and value of j:" + j); } System.out.println("************************"); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
value of i:1 and value of j:1 value of i:1 and value of j:2 value of i:1 and value of j:3 ************************ value of i:2 and value of j:1 value of i:2 and value of j:2 value of i:2 and value of j:3 ************************ value of i:3 and value of j:1 value of i:3 and value of j:2 value of i:3 and value of j:3 ************************ |
Note: Â Complete iteration of the inner loop would be single iteration for the outer loop
Exercise with solution (Triangle pattern)
Write a Java program to create the following pattern?
1 2 3 4 5 6 7 8 9 10 11 |
/* *@@ *@@@ *@@@@ *@@@@@ */ |
Solution
In this program, we write a Java program to print triangle pattern. We print symbol (@) in a line as well as a new line to generate a triangle pattern.
To generate triangle pattern we need two different loops for rows and columns, first is for printing each line and inner loops for printing pattern in each line. The outer loop will handle the number of rows and the inner loop will handle the number of columns.
1 2 3 4 5 6 7 8 9 |
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(); } } |
Output:
1 2 3 4 5 6 7 8 9 |
@ @@ @@@ @@@@ @@@@@ |
Contributed by: Poonam Tomar