A student executes the following code to increase the value of a variable ‘x’ by 2.
He has written the following statement, which is incorrect.
x = +2;
What will be the correct statement?
A. x +=2;
B. x =2;
C. x = x +2;
- (a)Only A
- (b)Only C
- (c)All the three
- (d)Both A and C
Show SolutionHide Solution↓
Both A and C
Reason — The student's code x = +2; is incorrect because it doesn't actually increment x by 2. Instead, it simply assigns the value +2 to x.
The correct way to increment the value of x by 2 is:
Option A:
x += 2;
This is shorthand forx = x + 2;and correctly incrementsxby 2.Option C:
x = x + 2;
This is the full, explicit version of incrementingxby 2. It is also correct.
Option B: x = 2;
This assigns 2 to x, which is not incrementing its value. Hence, this is incorrect.