Assignment CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
easyWhat is the difference between `x = 5` (assignment) and `x == 5` (comparison)?
Solution
- 1 Step 1: `x = 5` assigns the value 5 to the variable x. It changes x.
- 2 Step 2: `x == 5` compares x to 5 and returns TRUE or FALSE. It does not change x.
- 3 Step 3: Confusing these is a common bug โ using = instead of == in a condition.
Answer
`=` assigns a value; `==` checks for equality. They serve completely different purposes.
The distinction between assignment and comparison operators is fundamental. Many bugs arise from accidentally using one when the other is intended.
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 1 easy
Trace the following code: SET x = 10. SET y = x. SET x = 20. OUTPUT x, y.
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