Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# cert study guide problem

Otto Deckelman
Ranch Hand
Posts: 30
Hi Guys, can one of you explain the logic flow of this program step by step? And what would the output be? The cert guide just gives the answer but does not breakdown the logic.
Thanks. Otto.
class Question {
public static void main(String[] args) {
int i = 1;
int j = 2;
outer: while (i < j) {
++i;
inner: do {
++j;
if(i++ % 3 == 2) break inner;
else if(j++ % 3 == 1) break outer;
System.out.println(i*j);
} while (j< i);
System.out.println(i+j);
}
}
}

Ranch Hand
Posts: 688
The output is 6.
I'll give it a shot.
i = 1; j = 2;
At outer: (i < j) (true): i become 2;
At inner: j becomes 3

it's false, because, i++ is post-increment, that means the expression is evaluated first before i gets incremented. So
2 % 3 = 2 which == 2.
So the code will break out from inner, note that i is now 3.
this will print 6.
the while statement at outer is now false, since i = 3, j = 3.
Then, end of the program.
I hope this helps.

Otto Deckelman
Ranch Hand
Posts: 30
Thanks, it helps alot.

ryan burgdorfer
Ranch Hand
Posts: 219
[B]The output is 6.
I'll give it a shot.
i = 1; j = 2;
At outer: (i < j) (true): i become 2;
At inner: j becomes 3

it's false, because, i++ is post-increment, that means the expression is evaluated first before i gets incremented. So
2 % 3 = 2 which == 2.
So the code will break out from inner, note that i is now 3.

this will print 6.
the while statement at outer is now false, since i = 3, j = 3.
Then, end of the program.
I hope this helps.[/B]

The part in red confuses me...how does 2 % 3 == 2 ??
You yourself say first that it is false, then you go on to say that it is true...
confused.
------------------
• Ryan Burgdorfer
• Java Acolyte

Marilyn de Queiroz
Sheriff
Posts: 9063
12

Ryan,
2 divided by 3 equals zero, remainder 2 (2%3=2)

[This message has been edited by Marilyn deQueiroz (edited April 19, 2001).]

ryan burgdorfer
Ranch Hand
Posts: 219
duh...guh...buh
(sounds of idiocy)
I guess I was mislead by doing it on a calculator, and coming up with .666666...67
Actually, I have no excuse for this one
But I still don't understand why Adrian said "it's false"...then true...?