Lesson 9 of 12

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.

Start SET a = 7 SET b = 3 SET temp = a a = b b = temp OUTPUT a, b End
BEGIN
  SET a = 7
  SET b = 3
  SET temp = a
  a = b
  b = temp
  OUTPUT a, b
END

Variable Watch

VariableValue
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
1SET a = 77
2SET b = 373
3SET temp = a737
4a = b337
5b = temp377

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

  1. Right to left: The value on the right is stored in the variable on the left. x = 5 puts 5 into x.
  2. One value at a time: A variable can only hold one value. Assigning a new value erases the old one.
  3. Expressions are calculated first: In x = x + 1, the computer calculates x + 1 first, then stores the result back in x.
  4. 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 = value or variable = expression