Nested for loop in Java

Nesting a for loop inside a for loop is known as nested for loop.

We can nest n number of for loops inside for loops if needed.

General format

for(initialization;condition;increment/decrement) {

for(initialization;condition;increment/decrement) {

//statements or code to be executed

}

}

Example

Imagine 5 persons gave 5 number of coins each of different rupees to you, you want to add that, How will you add using programming?

Just assume number of persons and coins in a 2D array variable where first [] includes persons and 2 [] includes coins

public class NestedForLoop {

public static void main(String args[]) {

int persons[][]={{1,2,5,10},{1,2,5,10},{1,2,5,10},{1,2,5,10},{1,2,5,10}};

int sum=0;

for(int i=0;i<5;i++){

for(int j=0;j<4;j++){

sum=sum+persons[i][j];

}

}

System.out.println("Sum of coins is "+sum);

}

}

Try In Editor

Output

Sum of coins is 90

Above initialization is done like this, persons[0][0]=1,persons[0][1]=2,....;