I am a complete beginner and I’m trying to follow the logic behind this code snippet.
int x = 12;
do {
for (int w=9; w<x; w++)
System.out.print(w+” ”);
--x;
System.out.println(x);
}while (x>7);
When I run it, the answer is as follows:
9 10 11 11
9 10 10
9 9
8
7
If someone could explain how to read the code step by step in a simple way I would be very happy!
int x = 12;declare new local variable, calledxdo {begins newdo...whileloopfor (int w=9; w<x; w++)begins newforloop which will iterate until value of variablewis less then value of variablex. After each iteration of this loop variablewwill increase its value (byw++). Initial value of variablewis9(int w=9).System.out.print(w+” ”);this one prints out to console current value of variablewplus one white-space after that--x;this one decreases value ofxvariable. It is such called prefix version of operation--System.out.println(x);prints value ofxvariable to console and returns carriage(fixed thanks to Chris)}end offorloop code block} while (x>7);end ofwhilecode block with condition on which loop will end: until value of variablexis more then7loop will run.UPD: More specifically explaining output result:
1) 1-st iteration of
do loop. We havex == 12:iterations of internal
forloop:1.1)
w == 9,9 < 12=> outputs9to console1.2)
w++=>w == 10,10 < 12=> outputs10to console,1.3)
w++=>w == 11,11 < 12=> outputs11to console,1.4)
w++=>w == 12,12 == 12=> endsforloop2)
forloop ends.--x=>x == 11, outputs11to console and returns carriage, so we have line9 10 11 113) begins new iteration of
do ... whileloop withx == 11and so on untilxbecame equals to 7.