• 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
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

how nested loop works?

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Answer-012

I just want to understand how the nested loop works? In above example value of j is evaluated at every while loop iteration or not? Can anyone explain please?
 
Ranch Hand
Posts: 330
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy!

first, arrange the code in a more readable way. this helps to better understand what the code is trying to do:



In the code above, you'll see that the do/while loop contains an inner while loop. In the first iteration of the outer loop, the inner loop is executed and prints out k values: 012. In the second iteration (j is incremented), i is evaluated and since its value no longer satisfies the 'i++ < 3' condition (by virtue of the previous iteration), the inner loop does not execute and k value is never printed. 'j' again is incremented and performs another loop and so on.

hope this helps.
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
I have one another doubt.



How it's answer is "6,6"? I am not getting. Can anyone explain please?
 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class JMM117
{ public static void main (String[] args)
{ int i = 0, j = 9;
do {
i++;
System.out.println(" before if "+i+ ","+j);

if (j-- < i++) {break;}
System.out.println("After if "+i+ ","+j);
}
while (i < 5);
System.out.print("After do while"+i + "," + j);
}}

try this
you will understand
 
reply
    Bookmark Topic Watch Topic
  • New Topic