• 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
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

A simple q. abt. LOOP

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
class TestClass
{
public static void main(String args[ ] )
{
boolean b = false ;
int i = 1 ;
do
{
i++ ;
} while (b = !b) ;
System.out.println( i ) ;
}
}

//o/p=3
Unlike the while(){ } loop, the do {} while() loop executes atleast once and the condition is checked after the interation.The o/p shows that this loop is executing twice BUT how ?Pls..some1 explain it 2 me.
( Note that.. it is given 'b=!b' not 'b==!b')
THANKS IN ADVANCE.
Ratul Banerjee.
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by ratul banji:
Hi all,
class TestClass
{
public static void main(String args[ ] )
{
boolean b = false ;
int i = 1 ;
do
{
i++ ;
} while (b = !b) ;
System.out.println( i ) ;
}
}

//o/p=3
Unlike the while(){ } loop, the do {} while() loop executes atleast once and the condition is checked after the interation.The o/p shows that this loop is executing twice BUT how ?Pls..some1 explain it 2 me.
( Note that.. it is given 'b=!b' not 'b==!b')
THANKS IN ADVANCE.
Ratul Banerjee.


Hi Ratul,
You are right that the (do {} while) loop executes atleast once. So the first time, i++ inside the loop will yield 2.
Now while (b = !b) would be equivalent to while (b = !false) so b will true. (while(true)) will cause the loop to execute again.
This time i++ will yield a value of 3. Now come the while statement again. It will be evaluated as (b = !true) this time. So b will be false and that terminates the loop and i will retains the value of 3.
Hope that helps,
Lam
 
ratul banji
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Lam,

Many many THANKS.
When i saw the q. for the 1st time ,I missed the concept which u have written in the last para..
Thanks 1ce again.
Ratul
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic