Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cert study guide problem

 
Otto Deckelman
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
}
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, it helps alot.
 
ryan burgdorfer
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Adrian Yan:
[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: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic