Java for Inside for Statements
Nested for in java
Nested for is for loop inside for loop. for loop block can contain more for loop blocks. You can place multiple for loops inside one for loop. You can place for loops one inside the other.
nested for in Java - Syntax
for(initialization statement; termination statement that returns true or false; loop counter){ for(initialization statement; termination statement that returns true or false; loop counter){ statement; } }
for inside for - Java Example 1
public class NestedForLoop {
public static void main(String a[]){
for(int i=0; i<5;i++)
{
for(int j=5; j>0;j--)
{
System.out.print("" + i
+ "," + j + " | ");
}
System.out.println();
}
}
}
The above for loop prints0,5 | 0,4 | 0,3 | 0,2 | 0,1 | 1,5 | 1,4 | 1,3 | 1,2 | 1,1 | 2,5 | 2,4 | 2,3 | 2,2 | 2,1 | 3,5 | 3,4 | 3,3 | 3,2 | 3,1 | 4,5 | 4,4 | 4,3 | 4,2 | 4,1 |
for inside for in Java - Example 2
public class NestedForLoop2 {
public static void main(String a[]){
for(int i=0; i<2;i++)
{
for(int j=3; j>0;j--)
{
for(int k=0; k<2;k++)
{
System.out.print("" + i + ","
+ j + "," + k + " | ");
}
System.out.println();
}
System.out.println();
}
}
}
The above for loop prints0,3,0 | 0,3,1 | 0,2,0 | 0,2,1 | 0,1,0 | 0,1,1 | 1,3,0 | 1,3,1 | 1,2,0 | 1,2,1 | 1,1,0 | 1,1,1 |
for inside for - Java Example 3
public class NestedForLoop3 {
public static void main(String a[]){
for(int i=0; i<2;i++)
{
for(int j=3,k=0; j>0 && k<2;j--,k++)
{
System.out.print("" + i + ","
+ j + "," + k + " | ");
}
System.out.println();
}
}
}
This will print:0,3,0 | 0,2,1 | 1,3,0 | 1,2,1 |