Post

Created by @nathanedwards
 at November 1st 2023, 12:43:12 am.

AP Computer Science Exam Question

Consider the following code snippet:

int x = 5;
int y = 7;
int z = 3;

int result1 = x++ + --y * z;
int result2 = x-- - y++ % z;
int result3 = --x - y-- + ++z;

What are the values of result1, result2, and result3 after executing the above code? Show your step-by-step calculation.

Answer

To evaluate the expressions in each line, we'll follow the order of operations (PEMDAS/BODMAS). Let's go through each line step-by-step.

Line 1: int result1 = x++ + --y * z;

  1. x++ evaluates to the current value of x (5), and then increments x by 1.
    • x becomes 6.
    • result1 is temporarily set to 5.
  2. --y decrements y by 1 and evaluates to the new value (6).
    • y becomes 6.
    • result1 is temporarily set to 5 + 6 = 11.
  3. y * z multiplies the current value of y (6) by z (3).
    • result1 is temporarily set to 11 + 6 * 3 = 29.
  4. result1 is assigned the final value of 29.

Line 2: int result2 = x-- - y++ % z;

  1. x-- evaluates to the current value of x (6), and then decrements x by 1.
    • x becomes 5.
    • result2 is temporarily set to 6.
  2. y++ evaluates to the current value of y (6), and then increments y by 1.
    • y becomes 7.
    • result2 is temporarily set to 6 - 7 = -1.
  3. y % z finds the remainder when y (7) is divided by z (3).
    • result2 is temporarily set to -1 % 3 = -1.
  4. result2 is assigned the final value of -1.

Line 3: int result3 = --x - y-- + ++z;

  1. --x decrements x by 1 and evaluates to the new value (4).
    • x becomes 4.
    • result3 is temporarily set to 4.
  2. y-- evaluates to the current value of y (7), and then decrements y by 1.
    • y becomes 6.
    • result3 is temporarily set to 4 - 7 = -3.
  3. ++z increments z by 1 and evaluates to the new value (4).
    • z becomes 4.
    • result3 is temporarily set to -3 + 4 = 1.
  4. result3 is assigned the final value of 1.

Therefore, the final values are:

  • result1 = 29
  • result2 = -1
  • result3 = 1