Java do while loop increment

10,593

Solution 1

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

Solution 2

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 .

Solution 3

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

Share:
10,593
user1144004
Author by

user1144004

Updated on June 22, 2022

Comments

  • user1144004
    user1144004 almost 2 years
    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?