Labeled Boxes: How Programs Remember Things
Byte, a friendly glowing robot, stands beside a colorful wall of wooden boxes in a busy game room, carefully sliding numbered cards in and out of boxes labeled with tape name tags.
- Define a variable as a named container that holds one value.
- Identify the name and the current value of a given variable.
- Predict the new value stored after a program changes a variable.
- Explain how a stored value can be reused later in a program.
Key terms
- Variable
- A named box that holds one value.
- Name
- The label tag on the front of the box.
- Value
- The thing kept inside the box right now.
- Store
- To put a value into the box.
A Box With a Name
Think of a variable as a box with a name tag on the front. The tag might say score. Inside the box you keep one value, like the number zero. The name tells you which box you mean, and the value is whatever the box is holding at this very moment in the program.
Storing, Changing, and Reusing
A program can do three things with a box. It can store a value by putting a number inside. It can change the value by taking the old number out and putting a new one in. And it can reuse the value by peeking inside whenever it needs that number, like showing the score on the screen.
One Value at a Time
A box holds only one value at a time. When you put a new value in, the old value goes away. The name on the box never changes, but the value inside can change as often as you like. So always ask what is the name and what is inside it right now.
Worked examples
A box named lives holds 3. Store 2 into it.
- Take the old value 3 out of the box.
- Put the new value 2 inside the box.
Answer: The box named lives now holds 2.
A box named coins holds 5. Read its value.
- Peek inside the box without changing it.
- See the value that is sitting there.
Answer: The box named coins holds the value 5.
Activity
Match each box name on the left to the number it is holding on the right
Practice
A box named score holds 8. What value does it hold?
Name a box you might use to remember a player's points.
Common mistakes to avoid
- A box holds many valuesA box holds only one value at a time, never several at once.
- Variables cannot changeA program can change the value inside a box as often as needed.
Check your understanding
What is a variable in a program?
A variable named coins holds the number 4. The program stores 9 into coins. What number does coins hold now?
Recap
A variable is a named box that holds one value. A program can store a value, change it, and reuse it later. The name stays the same, but the value inside can change, and the box holds just one value at a time.
Reflect
What value would you like a box named score to hold?