Skip to main content

Java: Nested for Loop

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
Submitted by arilio666 on November 2, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.