Variables &
Assignments
Learn how computers store, update, and use data through variables: the fundamental building blocks of every program.
What Is a Variable?
A variable is a named container in a computer's memory that holds a value. Think of it like a labeled box: the label is the variable's name, and the contents are its current value.
Why Do Variables Matter?
Without variables, a program would have no way to remember information. Every calculation would be lost the moment it was computed. Variables let programs:
Common Data Types
Every value stored in a variable has a type that determines what operations you can perform on it.
The Assignment Operator
In programming, the assignment operator stores a value into a variable. The AP CSP exam uses the arrow notation:
Assignment vs. Equality
In math, \( x = 5 \) means "x equals 5, always." In programming, \( x \leftarrow 5 \) means "right now, put 5 into x." The value of x can change later.
| Math Equality | Programming Assignment | |
|---|---|---|
| Symbol | \( = \) | \( \leftarrow \) (or =) |
| Meaning | "is equal to" | "store this value" |
| Direction | Symmetric (both sides) | Right to left only |
| Can change? | No (permanent truth) | Yes (value can be overwritten) |
How Assignment Works Step by Step
Tracing Variables: Your Checklist
When the AP exam asks "What is the value of x after this code runs?", follow this tracing technique:
Example 1: Simple Assignment
Example 2: Overwriting Values
Example 3: The Swap Problem
How do you swap the values of two variables? You need a temporary variable:
Why Temp Is Essential
What happens if you try to swap without a temporary variable?
Expressions on the Right Side
The right side of an assignment can be any expression: a calculation involving numbers, variables, and operators that produces a single value.
Strings and Concatenation
Variables can also store text (strings). You can combine strings using concatenation: joining them end-to-end.
Common Mistakes
Summary: Key Concepts
| Concept | What It Means | Example |
|---|---|---|
| Variable | Named container for data | score, name |
| Assignment | Store a value (right \( \rightarrow \) left) | \( x \leftarrow 10 \) |
| Overwrite | New value replaces old | \( x \leftarrow 20 \) |
| Expression | Computed value on right side | \( z \leftarrow x + y \) |
| Swap | Exchange two values via temp | 3 assignments needed |
Question 1 of 5
What is the value of y after the following code executes?
Question 2 of 5
What is the value of a after this code runs?
Question 3 of 5
Which of the following correctly swaps the values of variables p and q?
Question 4 of 5
What does the following display?
Question 5 of 5
After the following code, what are the values of m and n?