Java: Nested for Loop

Profile picture for user arilio666

A loop within a loop is called a nested loop. In java nested for loop is the concept of nesting another loop within the main loop.

Syntax

for(initialization ; condition ; increment/decrement)
{
    for(initialization ; condition ; increment/decrement)
    {
        //body of nested loop
    }
    //body of the main loop
}

Example: Based On Star Count

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        for(int i = 1; i <= 4; i++)
        {
            for(int j = 1; j <= i ; j++)
            {
                System.out.println("*");
            }
            System.out.println("\n");
        }
    }
}

Output:

*

*
*

*
*
*

*
*
*
*
  • So here we have initialized i value as 1 which will be the condition of i <= 4 which means 1 to 4 and using that i within the loop we created another nested loop in that we have conveyed that we want this j too to be less than or equal to the result of i and print it in *.
  • And in the main body, we have said that print each iteration with a new line using \n.
Tags