Nested For Example Java Program

Definition

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

Syntax

for (initialization; condition ; increment) {
	for (initialization; condition ; increment) {
		//Do something
	}
}

Nested For Example Program

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

Sample Output

Output is:
1
12
123
1234
12345