user1144004
user1144004

Reputation: 302

Java do while loop increment

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?

Upvotes: 3

Views: 15307

Answers (3)

TMNT
TMNT

Reputation: 166

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); 

Upvotes: 2

Siva Kumar
Siva Kumar

Reputation: 2006

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 .

Upvotes: 3

Kaspar
Kaspar

Reputation: 112

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

Upvotes: 2

Related Questions