Q36.Marks: +2.0UGC NET Paper 2: Computer Sc 6th Jan 2025 Shift 1
Consider the following statements
int x = 10, y = 15;
x = ((x = y) ? (y + x) : (y - x));
What will be the value of x after executing these statements?
1.5
2.25
3.15
4.30✓ Correct
Solution
Explanation of the Correct Answer
The correct answer is 30.
Key Points
Let's break down the given code to understand how the value of x becomes 30.
The initial values are:
int x = 10;
int y = 15;
Next, we have the statement:
x = ((x = y) ? (y + x) : (y - x));
In the statement (x = y), x is assigned the value of y, so now x = 15.
In the ternary conditional operator ((x = y) ? (y + x) : (y - x)), since x = y results in x being non-zero (true in a Boolean context), the condition is true.
When the condition is true, the expression (y + x) is evaluated.
y is 15 and x is now 15, so y + x = 15 + 15 = 30.
Therefore, x = 30 after the assignment.
Additional Information
The ternary conditional operator is a shortcut for the if-else statement and is used to assign one of two values based on a condition.