Welcome to
Coderanch! Above your code is same like
When a for loop doesn't have { } braces then it can execute or we can say scope of that loop is only one line of code beneath that for loop statement.
Example:
It is same as below code
In your code outer i loop block scope contains
executed 5 times and inner j loop scope which contains
executed 15 times so output you get is 15 times ". "(dots)
Output:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Explanation:
When outer i loop starts executing i = 0 and then it executes inner j loop where it assigns j = i so now j =0, then j loop executes till j is less than 5 i.e. j < 5 returns true, so prints "." 5 times each dot on new line. When j becomes 5 then control comes out of inner j loop and executes System.out.println(" "); and prints blank space.
Now increments i so i becomes 1, again starts executing inner j loop by assigning j = i i.e. j = 1 again inner loop executed 4 times. Same process happens till i is less than 5 i.e. i <5 returns true.
Loop execution steps with values and condition check:
Steps | Value of i | Value of j | i < 5 ? | j < 5 ? |
---|
1 st time execution of outer i loop, At begining i = 0 |
1 | 0 | --- | Yes | --- |
2, Assigns j = i, Now j = 0 | 0 | 0 | --- | Yes |
3 | 0 | 1 | --- | Yes |
4 | 0 | 2 | --- | Yes |
5 | 0 | 3 | --- | Yes |
6 | 0 | 4 | --- | Yes |
7 | 0 | 5 | --- | No |
Executes System.out.println(" "); which is in outer i loop |
2nd time execution of outer i loop, Increments i, Now i = 1 |
8 | 1 | --- | Yes | --- |
9, Assigns j = i, Now j = 1 | 1 | 1 | --- | Yes |
10 | 1 | 2 | --- | Yes |
11 | 1 | 3 | --- | Yes |
12 | 1 | 4 | --- | Yes |
13 | 1 | 5 | --- | No |
Executes System.out.println(" "); which is in outer i loop |
3rd time execution of outer i loop, Increments i, Now i = 2 |
14 | 2 | --- | Yes | --- |
15, Assigns j = i, Now j = 2 | 2 | 2 | --- | Yes |
16 | 2 | 3 | Yes | Yes |
17 | 2 | 4 | Yes | Yes |
18 | 2 | 5 | Yes | No |
Executes System.out.println(" "); which is in outer i loop |
4th time execution of outer i loop, Increments i, Now i = 3 |
19 | 3 | --- | Yes | --- |
20, Assigns j = i, Now j = 3 | 3 | 3 | --- | Yes |
21 | 3 | 4 | --- | Yes |
22 | 3 | 5 | --- | No |
Executes System.out.println(" "); which is in outer i loop |
5th time execution of outer i loop, Increments i, Now i = 4 |
23 | 4 | --- | Yes | --- |
24, Assigns j = i, Now j = 4 | 4 | 4 | --- | Yes |
25 | 4 | 5 | --- | No |
Executes System.out.println(" "); which is in outer i loop |
6th time execution of outer i loop, Increments i, Now i = 5 |
21 | 5 | --- | No | --- |
Control comes out of outer i loop b'cause i <5 returns false |