0
int a=0; for (a=0; a++<=10;) { System.out.print(a+ " "); } Output: 1 2 3 4 5 6 7 8 9 10 11 

Why does it prints 11 when the loop is said to end when the variable “a” reaches 10 also why it doesn’t start with 0 as postfix operator is used?

int a=3, b=4; int c = a + b++; System.out.println(+c); Output: 7 

Why the postfix increment operator doesn’t add a value in variable ‘b’? Shouldn't the output be like ‘8’?

0

1 Answer 1

2

a++ means use the value for a, then add 1.

So the first one will read the value of a as 10, then add 1, so it prints a value of 11.

The second one reads b as 4, so c=3+4=7. b becomes 5 after the addition is completed.

Sign up to request clarification or add additional context in comments.

4 Comments

if that's correct then why series doesn't start with 0?
@user2015669: Because by the time you use it in your println, it's already been incremented. The operator is in the for condition, so the for condition uses the old value. Then the body of the for is executed with a having the new value.
When the condition is being checked in the for part, a=0. But after it was checked, it was incremented to a=1. So it will print 1 and not 0.
Thanks a lot for clearing up my concepts!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.