Currently I am studying for my Java test. Whist studying I've come across a small problem.
In this for loop:
for ( int i=1; i <= 3 ; i++ ) {
for (int j=1; j <= 3 ; j++ ) {
System.out.println( i + " " + j );
}
}
The output is:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
My problem is, I don't understand it. When I read this code I keep thinking it should look like this:
1 1
2 2
3 3
Why is this not the case?
A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc.
Syntax. do { statement(s); do { statement(s); }while( condition ); }while( condition ); A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.
Each iteration of i, you're starting a completely new iteration of j.
So, you start with i==1, then j==1,2,3 in a loop. Then i==2, then j==1,2,3 in a loop, etc.
Step through it one step at a time, and it will make sense.
What you have is one loop inside of another. Think of it like the minute hand and the hour hand on a clock. The minute hand is going to go around (1,2,3,4...59) while the hour hand is still on 1. So, if we treat hours as i, and minutes as j, we have:
1 1
1 2
1 3
...
1 60
And then the hours change to 2, and the minute hand keeps going around:
2 1
2 2
2 3
...
2 60
And we finish once we get to
12 1
12 2
12 3
...
12 60
which is where the loop ends. Your example is much like this.
(For the pedantic, I know it's zero-based, but in order to illustrate, this may be easier to understand)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With