Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

do while loop

 
Clay Chow
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


One question,
is


do while (boolean) {}

equivalent to

while (boolean) {}


?
[ November 26, 2008: Message edited by: Clay Chow ]
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Clay Chow:


One question,
is


do while (boolean) {}

equivalent to

while (boolean) {}


?

[ November 26, 2008: Message edited by: Clay Chow ]


When you use do while it means statements inside the loop will be executed irrespective condition mentioned in while() is true or not. It will be executed at least once. But in case of while loop, statements inside the loop will be executed if and only if condition mentioned in while() is true.
 
Patel Chintan
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Patricia Samuel:


When you use do while it means statements inside the loop will be executed irrespective condition mentioned in while() is true or not. It will be executed at least once. But in case of while loop, statements inside the loop will be executed if and only if condition mentioned in while() is true.


int w = 0;
do while ( w < 1 )
System.out.print( "w is " + w );
while ( w > 1 ) ;

Is is similar to:
[edit]Add code tags. CR[/edit]
[ November 26, 2008: Message edited by: Campbell Ritchie ]
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did i misinterpret the question?

Wasn't Clay asking the difference between do while() and while()

 
Campbell Ritchie
Sheriff
Posts: 48646
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks like a question from an exam; please quote where you got it from.
It is a confusing loop; it is actually an endless loop inside a do-loop. Patel Chintan: you got it right, but you ought to use the code tags, which I have added so you can actually read the code.

In these questions, they often quote incorrectly-indented code so as to confuse the examinees.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One question,
is

do while (boolean) {}

equivalent to

while (boolean) {}


no. taken as written, there is no such thing as a "do while (boolean) {}" construct. you can have a while loop:



or you can have a do-while loop:



in your example in the original post, what you have is a while loop inside a do-while loop:


[ November 26, 2008: Message edited by: fred rosenberger ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic