Assignment CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumTrace the values of x and y after each line:
SET x = 10
SET y = x + 5
SET x = y * 2
SET y = x - y
What are the final values of x and y?
Solution
- 1 Step 1: SET x = 10 โ x is 10.
- 2 Step 2: SET y = x + 5 โ y is 10 + 5 = 15.
- 3 Step 3: SET x = y * 2 โ x is 15 ร 2 = 30. (y is still 15.)
- 4 Step 4: SET y = x - y โ y is 30 โ 15 = 15.
Answer
x = 30, y = 15. Assignment uses the current value of the right-hand side at the moment it executes, so the order of statements matters.
Tracing sequential assignments reinforces the idea that each statement reads the current value of every variable on the right-hand side, computes the result, and then stores it in the left-hand variable.
About Assignment
The operation of storing a value in a variable. The variable name goes on the left of the assignment operator, and the value or expression goes on the right. The right side is evaluated first, then the result is stored in the variable on the left.
Learn more about Assignment โ