• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

can someone explain this?

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class test {
public static void main (String[] args) {
int i = 0, j = 0;
while (i++ < 3) do
System.out.print(j);
while (j++ < 3);
}}
how do you get the output 012345
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Notice that the do-while loop is the body of the first while loop.

So until j become 3, j is going to be printed

012

Now j is 3.

i is incremented but the do while runs again.

Remember that in a do-while, you execute the body of the loop before you check the condition.

So that is why j is printed again until i becomes 3

345
[ June 21, 2006: Message edited by: Keith Lynn ]
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
while (i++ < 3) //outer while
{
//System.out.println("with in outer while "+i);
do //inner do while.
System.out.print(j);
while (j++ < 3);
//System.out.println("with in outer while "+j);
}

In outer while, i value is used and then incremented. hence it runs for i 0,1,2. for these iterations, do while is executed.

Let us take one by one.
for i = 0.
point to note, in do while, statements are executed atleast once. So it prints 4 values 0,1,2,3. by the end of this do while execution, j becomes 4.

for i = 1.
again do while is executed and current j value 4 is printed. since the condition j++ <3 (4<3,j becomes 5) is not satisfied,it doesnot loop again.

for i = 2
do while executes once and prints 5 ,j becomes 6.

Keep Sop statements,such that you get to know the flow.
 
lavanya sankuappan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for all your explanations
 
Whatever. Here's a tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic