File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

loop

 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the following code, the answer given is 121212
class JMM110 {
public static void main (String[] args) {
int j = 0;
do for (int i = 0; i++ < 2
System.out.print(i);
while (j++ < 2);
}}

Can anybody pl explain?Thanks
[ May 22, 2004: Message edited by: Barry Gaunt ]
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did a proper indentation for the code you've posted in order to make it easier to understand.



Pay attention for the following:
1) do-while loop is always executed at least once.
2) i++ and j++ return its old value, then increment it.

Knowing this, give it another shot, and trace it again. If you still can't understand the answer, i'll explain it more in detail.
[ May 22, 2004: Message edited by: Vicken Karaoghlanian ]
 
Voggy Horla
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the conditional expression
(i++ < 2)
will be executed before print the i.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good approach to understanding such problems is to run the code. You can also put additional print statements in to check the values of the variables i and j. There is also the technique of using a symbolic debugger such as that provided by the free Eclipse IDE. And there is also the java debugger jdb.
 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I understood.Thanks a lot!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic