Variables & Assignment
Think of a variable as a labeled box that holds a value. You can put a number in the box, look at what's inside, or replace it with something new. Variables are how programs remember things.
A variable is a named storage location that holds a value. An assignment puts a value into a variable. The old value is replaced — you can only store one thing at a time.
How Assignment Works
When you see SET x = 5, it means "put the value 5 into the box labeled x."
If x already had a value, the old value is thrown away and replaced with 5.
The key thing: assignment goes right to left. The value on the right side
gets stored in the variable on the left side. So x = y + 1 means "calculate
y + 1, then store the result in x."
Example: Swapping Two Variables
Here's a classic problem: you have two variables, a and b, and you
want to swap their values. You can't just write a = b because you'd lose the
original value of a! You need a temporary variable to hold
one value while you swap. Watch the Variable Watch panel carefully.
BEGIN
SET a = 7
SET b = 3
SET temp = a
a = b
b = temp
OUTPUT a, b
END
Variable Watch
| Variable | Value |
|---|---|
| Step through to see variables | |
The trick is the temporary variable. Without it, you'd lose a value during the swap. Here's what happens step by step:
| Step | Action | a | b | temp |
|---|---|---|---|---|
| 1 | SET a = 7 | 7 | — | — |
| 2 | SET b = 3 | 7 | 3 | — |
| 3 | SET temp = a | 7 | 3 | 7 |
| 4 | a = b | 3 | 3 | 7 |
| 5 | b = temp | 3 | 7 | 7 |
Why can't you just write a = b then b = a?
Because after a = b, both variables hold the same value! The original value
of a is gone. That's why you need temp to save it first.
Key Rules of Assignment
- Right to left: The value on the right is stored in the variable on the left.
x = 5puts 5 into x. - One value at a time: A variable can only hold one value. Assigning a new value erases the old one.
- Expressions are calculated first: In
x = x + 1, the computer calculatesx + 1first, then stores the result back in x. - Order matters: Changing the order of assignments can give completely different results.
Key Takeaways
- A variable is a named box that holds one value at a time.
- Assignment (
SET x = 5) stores a value in a variable, replacing any previous value. - Assignment goes right to left: the right side is calculated first, then stored in the left side.
- To swap two variables, you need a temporary variable — otherwise you lose a value.
- In pseudocode:
SET variable = valueorvariable = expression