• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

While loop and Do-while doubt.

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Keith.I got it.
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Peter.I have changed it to "x+=x" for printing x=4 value.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic