Assignment CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
easyTrace the following code: SET x = 10. SET y = x. SET x = 20. OUTPUT x, y.
Solution
- 1 Step 1: x is assigned 10.
- 2 Step 2: y is assigned the current value of x, which is 10. So y = 10.
- 3 Step 3: x is reassigned to 20. y is unchanged (still 10). Output: x = 20, y = 10.
Answer
x = 20, y = 10.
Assignment copies the current value, not a reference. Changing x later does not affect y because y received the value (10), not a link to x.
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 โMore Assignment Examples
Example 2 easy
What is the difference between `x = 5` (assignment) and `x == 5` (comparison)?
Example 3 easyWhat is the output? SET a = 3. SET b = 4. SET a = a + b. SET b = a - b. OUTPUT a, b.
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