I’m trying to read the output of this code, but it simply just doesn’t make sense to me.
Even after learning that a loop without braces only loops through the first line, the output still makes no sense, at all. Some numbers do, but others just don’t.
My code:
int n = 8;
int i = 1;
int j = 1;
j = n + 2;
System.out.println (n + " " + i + " " + j );
while (n > 1)
{
n = n/2;
for (i = 2; i <= n; i = i+2)
System.out.println (n + " " + i + " " + j );
j++;
}
System.out.println (n + " " + i + " " + j );
And it outputs:
8 1 10
4 2 10
4 4 10
2 2 11
1 2 13
I get the 8-1-10
and the 4-2-10
but anything after that, I’m stumped, I don’t get how the computer calculates the rest.
Would someone mind going through the rest of the output with me, step by step?
Thank’s in advance.
No braces means that the loop affects only the next statement that follows the loop.
So
is equivalent to
Usually, indentation is used in those cases to make the code more comprehensible, like this:
EDIT: Now, this is the actual answer to the question. It all depends on the different iterations the loop does and how do the variables get incremented.
Now, on with the iteration:
For the first iteration, we have
n=8 i=1 j=10, so sincen > 0istruethe loop takes place.Then, the
for(note that it just assigns the value2toi):Since
n = 4, the only values thatican take are2and4, then the prints are:After that,
jis incremented by one, making itj = 11. The condition for thewhileis met again becausen = 4.n = n/2makesntake the value2, so it enters thewhile again. Let’s take a look at the for again:This time, the only value that
ican take is2(note that the value ofiis reset again to2while starting the iteration), and that’s the print you get.Before iterating again,
j++makesjhave the value12.On the final iteration,
n = n/2results inn = 1since n is anintbut this is done inside the while, so it enters again. Now thatn = 1the loop looks like this:iis set to2and the condition for the for is not met (2 <= 1isfalse). Then there is no print this time, yetjis incremented to13at the end of the while.In the next iteration you have
n = 1, that means that thewhile‘s condition is not met so the iteration breaks. Finally you haven = 1,i = 2andj = 13. That’s the last print you get.