posted 4 years ago

Help me to understand this code....

class Try

{

public static void main(String[] args)

{

int i = 10;

while (i++ <= 10) {

i++;

}

System.out.print(i);

}

}

Result is 13

I can't Understand why it is 13..

class Try

{

public static void main(String[] args)

{

int i = 10;

while (i++ <= 10) {

i++;

}

System.out.print(i);

}

}

Result is 13

I can't Understand why it is 13..

Abhishek Boppudi

Greenhorn

Posts: 8

posted 4 years ago

At the end of the first iteration it is 12. then the while loop checks for the condition again and i++ gives 13 and come out of the loop.

on the first iteration.

i is 10 and incremented by 1 in the while condition.

condition passes and again i is incremented by 1, now it is 12.

then while checks for the condition again and this time it gets incremented by 1.

so it is 13.

on the first iteration.

i is 10 and incremented by 1 in the while condition.

condition passes and again i is incremented by 1, now it is 12.

then while checks for the condition again and this time it gets incremented by 1.

so it is 13.

posted 4 years ago

The loop continues as long as the result of the expression

Try imagining in your head, line by line, what happens.

First, i is equal to 10. Then we get to the

`while (i++ <= 10)`

The loop continues as long as the result of the expression

`i++`is less than or equal to 10. So, it stops iterating as soon as the result of the expression is > 10.

Try imagining in your head, line by line, what happens.

First, i is equal to 10. Then we get to the

`while`line. Remember what I wrote in my first reply about what

`i++`does. What happens to the variable

`i`? What is the result of the expression

`i++`? What is the result of

`i++ <= 10`(is it

`true`or

`false`)? What happens next? Etc.