Consider the following code segment: if (Y < 0) {X = -X; Y = -Y;} Z = 0; while…
2017
Consider the following code segment: if (Y < 0) {X = -X; Y = -Y;} Z = 0; while (Y > 0) {Z = Z + X; Y = Y - 1;} Assume that X, Y and Z are integer variables , and that X and Y have been initialized . Which of the following best describes what this code does?
- A.
Sets Z to be the product X * Y
- B.
Sets Z to be the sum X + Y
- C.
Sets Z to be the absolute value of X
- D.
Sets Z to be the value of Y
Attempted by 118 students.
Show answer & explanation
Correct answer: A
Let X0 and Y0 denote the initial values of X and Y.
If Y < 0 then Y becomes -Y (making Y positive) and X becomes -X (flipping X's sign). This preserves the overall sign of the product.
Z is set to 0, and the while loop adds the current X to Z exactly Y times.
Therefore after the loop Z equals the product of the current X and Y; because X and Y were adjusted when Y was negative, Z equals the product of the original X and Y (X0 × Y0).
Example: if original X = 3 and original Y = -2 then after the if-statement X becomes -3 and Y becomes 2; the loop adds -3 twice so Z = -6, which equals 3 × -2.
Conclusion: Z becomes the product of the original X and Y.