Write the result stored in x after evaluating the following expression? [2]
int x = 4; x + = (x++) + (++x) + x;
Answers
Answered by
7
- The final value of x is - 20.
Given:
> x = 4
On evaluating the expression:
> x+= x++ + ++x + x
> x = x + x++ + ++x + x
> x = 4 + x++ + ++x + x [Substitute the value]
> x = 4 + 4 + ++x + x [x remains 4, post-increment]
> x = 8 + ++x + x [x becomes 5]
> x = 8 + 6 + x [x becomes 6, pre-increment]
> x = 14 + 6
> x = 20 (Answer)
⊕ So, the final value of x is 20.
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
Similar questions