• Post Reply Bookmark Topic Watch Topic
  • New Topic

While loop and Do-while doubt.  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


While loop is working good.Within the loop, printed x=2 first time and then x=2+2 and when it entered the return statement it came out of the loop and it jumps back to the calling method.

But when I write the above statement using do-while loop



It gave me unreachable code error.How? Can anyone please explain it to me.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference between a while and a do-while loop is that the body of the while loop is not necessarily going to execute.

However the body of a do-while will execute the first time.

In the loop you have a return statement.

So the first return statement will be executed, meaning you can never get to the second.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Keith.I got it.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, "x += x++". Wha?

I've been programming C-like languages, such as Java, for 10 years and I'm not confident what "x += x++" actually does, without spending 10 minutes consulting documentation.

Perhaps this is part of some homework or assignment, where you have to understand what a weird statement like that does.

If not, then that is the type of weirdness that you should avoid like the plague in your programming. Rewrite the expression more clearly, perhaps even using two statements, if that makes it clearer.
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter.I have changed it to "x+=x" for printing x=4 value.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!