Nested For Loop in Java


The for loop in Java is an entry-controlled loop. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The three components of the for loop (separated by ;) are variable declaration/initialization (here int i = 0), the condition (here i < 100), and the increment statement (here i++).

The variable declaration is done once as if placed just inside the { on the first run. Then the condition is checked, if it is true the body of the loop will execute, if it is false the loop will stop. Assuming the loop continues, the body will execute and finally when the } is reached the increment statement will execute just before the condition is checked again.

Any looping statement having another loop statement inside called nested loop. The same way for looping having more inner loop is called 'nested for loop'..

Syntax:
   for( initial ; Condition ; increment / decrement )  // Outer Loop Statements
   {
      for( initial ; Condition ; increment / decrement )  // Inner Loop Statements
      {
          . . . .
      }
   }

Source Code

public class nested_for {
    public static void main(String args[]) {
 
        for(int i=1;i<=5;i++)//1<=5 2<=5
        {
            for(int j=1;j<=5;j++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}
 

Output

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
To download raw file Click Here

Basic Programs