Krivalar Tutorials 
Krivalar Tutorials

Java for Inside for Statements


<<Previous

Next >>





Nested for Statement

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;
	}
}
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 prints
0,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 |

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 prints
0,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 |

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 |


<<Previous

Next >>