Multiple choice technology programming languages

Consider the following code: int x, y, z; y = 1; z = 5; x = 0 - (++y) + z++; After execution of this, what will be the values of x, y and z?

  1. x = 4, y = 1, z = 5

  2. x = 3, y = 2, z = 6

  3. x = -7, y = 1, z = 5

  4. x = 4, y = 2, z = 6

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

To solve this question, the user needs to know the order of operations in C programming and the difference between pre-increment and post-increment operators.

First, let's break down the expression x = 0 - (++y) + z++:

  1. ++y is a pre-increment operator, which means it increments the value of y by 1 before the value is used in the expression. So, y becomes 2.
  2. z++ is a post-increment operator, which means it increments the value of z by 1 after the value is used in the expression. So, z remains 5 in this expression.
  3. The expression inside the parentheses is evaluated first, so ++y is evaluated to 2.
  4. Next, the multiplication and division are evaluated from left to right, but there are none in this expression.
  5. Finally, the addition and subtraction are evaluated from left to right.

So, 0 - (++y) evaluates to -2 and z++ evaluates to 5, therefore the whole expression evaluates to -2 + 5 = 3.

Therefore, the correct answer is:

The Answer is: B. x = 3, y = 2, z = 6

AI explanation

Walking through the code: y = 1; z = 5; initially. In x = 0 - (++y) + z++;, ++y is pre-increment, so y becomes 2 before use, and that value (2) is used in the expression. z++ is post-increment, so the current value of z (5) is used in the expression first, and z is incremented to 6 afterward. So x = 0 - 2 + 5 = 3. Final values: x = 3, y = 2 (already incremented), z = 6 (incremented after use). This matches 'x = 3, y = 2, z = 6'. The other options either use the wrong (pre- vs post-increment) value for y or z, or fail to apply the increments to the variables themselves.