I just learnt about Looping, Pre and Post increment, but I think I didn’t understand it.
Can someone explain this code loop by loop. Thanks in advance.
class Multi
{
public static void main(String[] args)
{
for(int x = 0; x < 4; x++)
{
for(int y = 4; y > 2; y--)
{
System.out.println(x + " " + y);
}
if(x == 1)
{
x++;
}
}
} }
the output for the above code is :
0 4
0 3
1 4
1 3
3 4
3 3
When I tried to find the output I got confused in the second iteration when x value is equal to 1 and it’s incremented to 2 I think.So I looked into the solution and pasted above.
and increments x by one after each iteration of the loop body
for(int y = 4; y > 2; y--) {
System.out.println(x + " " + y);
}
The inner loop
initializes y to 4
checks that y < 2
and decrements y by one after each iteration of the loop body
if (x == 1) {
x++;
}
This if statement checks if x has the value 1. If it does, the x value is incremented by 1. It is within the body of the first for loop, and it is executed before the loop’s first statement for(int x = 0; x < 4; x++) increments x. The effect in your example is that the inner loop (with your print statement) is effectively skipped when x == 2.
In other words, when x == 1, the flow is like