Java does while while 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 i_final

- 32

and not 31

? As we can see, the loop was do_while

executed only once, so line 8 should also be executed only once, hence increasing the value of "i" by 1. When 31

increased to 32

?

+3


source to share


3 answers


when you do a while loop like (i ++ <15) it checks the condition and stops the loop if i ++ is <15, but here when you do while while j ++ the loop goes 2 times and when it comes (i ++ <15) it increments the value of i by 1 and stops ... so in the second loop the value of i is incremented 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 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); 

      

+2


source


While the loop will execute twice before it is interrupted.

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

      

At first, it increases to 11.

Check from 15. Returns true.



Now it increases to 31. ( i = i + 20

)

now in a loop again.

it increases the value.

+3


source


The first time the condition of the while loop is checked i = 11, after that i is incremented by 20, so i = 31. Then when the condition is checked again, when 31 <15 is found to be false, it is still incremented by 1. So i = 32

+2


source







All Articles