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.

Output:

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 a following pattern?

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.

Output:

@

@@

@@@

@@@@

@@@@@

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu