by Dinesh Thakur Category: Control Structures

Like the nesting of if and other looping statements, the for loop can also be nested. In other words, we can have a for loop in the body of other for loop. There is no restriction on the level of nesting of loops but one should take care while nesting at multiple levels otherwise unexpected results may arise.

To illustrate the concept of nested for loop, let us consider a program to generate a pyramid of numbers.

//Program to Display Pyramid

import java.util.Scanner; //Program uses Scanner class
 public class pyramid
    public static void main(String [] args)
        int n,i,j;
        //create scanner object to obtain input from keyboard
        Scanner input =new Scanner(;
        System.out.print("Enter How Many Lines :"); // input
        n =input.nextInt(); //Read number
        for(i=1 ; i<=n ; i++ )
               for( j=1; j<=i ; j++)
                       System.out.print(i + " ");

Nested For Loop in Java Example

On execution, we first input the number of lines n (say 10). In this program, the inner j loop is nested inside the outer i loop. For each value of variable i of outer loop, the inner loop will be executed completely. For the first iteration of outer loop, the outer loop variable i is initialized to 1 and the inner loop is executed once as the condition (j < =i) is satisfied only once, thus prints the value of i (i.e. 1) once.

The statement Systam.out.print (ā€œ\nā€) i must be outside the inner loop and inside the outer loop in order to produce exactly one line for each iteration of the outer loop.

On second iteration (pass) of outer loop, when i=2 then the inner loop executes 2 times and thus displaying value of i (i.e. 2) 2 times and process will continue until the condition in the outer loop becomes false.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles