What will be the final value of a when a=2 initially. a+=a++ +(++a) +(--a) - (a--)--a;
Answers
ANSWER.
- The final value of a = 9.
SOLUTION.
Given,
> a = 2
> a += a++ + ++a + --a - a-- + --a
> a = a + a++ + ++a + --a - a-- + --a
> a = 2 + 2 + ++a + --a - a-- + --a (Value of a is not changed, post-increment)
> a = 4 + ++a + --a - a-- + --a (a becomes 3)
> a = 4 + 4 + --a - a-- + --a (a becomes 4, pre-increment)
> a = 8 + --a - a-- + --a
> a = 8 + 3 - a-- + --a (a becomes 3, pre-decrement)
> a = 11 - a-- + --a
> a = 11 - 3 + --a (Value of a is not changed, post-decrement)
> a = 8 + --a (a becomes 2)
> a = 8 + 1 (a becomes 1, pre-decrement)
> a = 9
★ So, the final value of a is 9.
LEARN MORE.
There are two types of increment/decrement operations.
- Post increment/decrement.
- Pre increment/decrement.
Post Increment/Decrement – Here, operation takes place first and then the value is incremented/decremented.
Example –
> int a = 2;
> int b = a++;
> b = 2
Now, a = 3.
Pre Increment/Decrement – Here, value is first increment/decrement and then the operation is carried out.
Example –
> int a = 2;
> int b = ++a;
> b = 3
Also, a = 3