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
?
source to share
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);
source to share