3
int i = 10; 
int j = 0; 
do { 
    j++; 
    System.out.println("loop:" + j); 
    while (i++ < 15) {                //line6 
         i = i + 20; 
         System.out.println(i); 
    } ; 
} while (i < 2); 
System.out.println("i_final:" + i); 

Output:

loop:1 
31 
i_final:32

Why the i_final is 32 and not 31? As we can see the do_while loop has executed only once, so line 8 should also have executed only once, hence incrementing the value of "i" by 1. When did 31 increment to 32?

1
  • 4
    The contents of the while loop has executed once, but the condition has been checked twice. Commented Dec 14, 2014 at 11:27

3 Answers 3

3

While loop will be executed twice before its break.

while (i++ < 15) {                //line6 
                i = i + 20; 
                System.out.println(i); 
            } ;

First it increment to 11 .

Check with 15. Returns true.

Now it increments to 31. (i = i + 20)

now again while loop .

it increments the value .

Sign up to request clarification or add additional context in comments.

Comments

2

when you are doing a while loop as (i++ < 15) , it checks the condition and stop the loop if i++ is < 15 , But here when you do a do while loop j++ the loop goes 2 times and when it comes to while (i++ < 15) it increaments the value of i by 1 and stops... so in second loop the value of i increases by one but the function inside the while loop remains the same as it stops when i++ is > than 15

IF you do the following you will get 31

int i = 10; 
int j = 0; 
    do { 
    j++; 
    System.out.println("loop:" + j); 
    while (i < 15) {                //line6 
         i++
         i = i + 20; 
         System.out.println(i); 
    } ; 
} while (i < 2); 
System.out.println("i_final:" + i); 

1 Comment

i think you mean to put do{}while(j<2) ... besides i < 2 ... at the end of the do while loop
2

First time when while loop condition is checked i=11, after that i is incremented by 20, so i=31. Then while condition is checked again, when found that 31 < 15 is false i is still incremented by 1. So i =32

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.