AP Computer Science Principles · Study guide

Variables and Assignments

AP® Computer Science Principles · Big Idea 3 · Algorithms and Programming

Variables and Assignments

What a variable is, which type of value fits which job, and how the assignment arrow changes a value, one copy at a time.

1What a variable is

A variable is a name in a program that stands for a value. Behind the name is storage that holds one value at a time. That one value can be a list or other collection, which in turn holds many values. Think of a labelled box: the label stays the same, and what is inside can be swapped out.

A variable is an abstraction: the program can work with score without caring where or how the computer stores it. You only need the name.

Figure 1. A variable is a name attached to storage for one value. That one value can be a list that holds many values.

2Types of values

Many programming languages give data a type. The four you will meet most are numbers, Booleans (true or false), strings (text), and lists. Some values fit one type better than another. Ask what you will do with the value.

ValueBest typeWhy
Number of tickets soldnumberYou add to it and compare sizes
Whether the door is lockedBooleanIt is only ever yes or no
Phone number “0412 555 019”stringThe leading 0 and the spaces must be kept; you never do arithmetic on it
ZIP code “02134”stringAs a number it would lose its leading 0 and become 2134
Test scores for a whole classlistMany related values under one name

Digits do not make something a number. "7" in quotes is a string, one character long, and joining it to "1" gives "71", not 8.

3Names that explain

The computer runs these two programs the same way, and both display 51.36. Only one of them tells a person what is going on.

Runs, but says nothing
x ← 48.00
y ← 0.07
z ← x + x * y
DISPLAY(z)
Runs, and explains itself
price ← 48.00
taxRate ← 0.07
total ← price + price * taxRate
DISPLAY(total)

Meaningful variable names make code easier to read and make it clear what each value represents. Good names are also clues when you read someone else’s code: count, total, and isFound tell you what to expect inside.

4The assignment arrow

Reference language
a ← expression

The assignment operator ← is how a program changes the value a variable represents. It works in two steps, in this order: first evaluate the expression on the right, then store a copy of the result in the variable on the left.

Because the right side is worked out first, a variable can appear on both sides:

points ← 10
points ← points + 5
points ← points * 2
DISPLAY(points)

points goes 10, then 15, then 30. In each line the right side reads the old value and the left side receives the new one. The program displays 30.

The value stored in a variable is always the most recent value assigned to it. And assignment copies; it does not tie two variables together:

a ← 1
b ← a
a ← 2
DISPLAY(b)
Figure 2. b ← a stores a copy of the value a has at that moment. Changing a afterward does not reach b.

The segment displays 1, not 2. The second line gave b a copy of the 1 that a held then. The third line changed a and nothing else.

Lists follow the same rule. After best ← scores, best holds its own copy of the list, so changing scores later does not change best.

The key idea

a ← expression evaluates the expression, then stores a copy of the result in a. A variable holds one value at a time, and its value is whatever was assigned to it most recently.

5Tracing assignments

To find what a segment displays, use a trace table: one row per statement and one column per variable. In each row, change only the variable on the left of the arrow, and copy the others down from the row above.

x ← 5
y ← x
x ← x + 3
y ← y * x
DISPLAY(x)
DISPLAY(y)
Statementxy
x ← 55
y ← x55
x ← x + 385
y ← y * x840

An empty cell means the variable has not been given a value yet. The segment displays 8 and then 40. Notice that line 3 changed x but left y at 5: y got a copy of the old x.

6Swapping two values

Swapping two variables shows why copying matters. The obvious attempt fails:

x ← 4
y ← 9
x ← y
y ← x
DISPLAY(x)
DISPLAY(y)
Statementxy
x ← 44
y ← 949
x ← y99
y ← x99

Line 3 overwrites x with 9, and the 4 is gone for good. Line 4 then copies that 9 back into y. It displays 9 and 9. The fix is to save one value in a third variable before overwriting it:

x ← 4
y ← 9
temp ← x
x ← y
y ← temp
DISPLAY(x)
DISPLAY(y)
Statementxytemp
x ← 44
y ← 949
temp ← x494
x ← y994
y ← temp944

Now it displays 9 and 4: the values traded places.

7Worked examples

Worked Example 1 Trace

Square, then add

What is displayed?

n ← 2
n ← n * n
n ← n + 1
DISPLAY(n)
  1. 1
    Line 1: n is 2.
  2. 2
    Line 2: evaluate n * n with the current value, 2 × 2, so n becomes 4.
  3. 3
    Line 3: n + 1 is 5.
Answer: 5
Worked Example 2 Trace

Two variables trading information

What is displayed?

a ← 3
b ← a + 4
a ← b - a
b ← a * 2
DISPLAY(a)
DISPLAY(b)
  1. 1
    One row per statement:
    Statementab
    a ← 33
    b ← a + 437
    a ← b - a47
    b ← a * 248
  2. 2
    Line 3 uses the values from the row above: b - a is 7 − 3.
Answer: 4 then 8.
Worked Example 3 Choose a type

Store it well

A sign-up app stores (a) a student ID like “00731”, (b) how many events the student has attended, (c) whether the student has paid, (d) the student’s five favorite clubs. Choose a type for each.

  1. 1
    (a) A string: the leading zeros are part of the ID, and no one adds IDs together.
  2. 2
    (b) A number: it is counted and compared.
  3. 3
    (c) A Boolean: paid or not paid.
  4. 4
    (d) A list: several related values under one name.
Answer: String, number, Boolean, list.
Worked Example 4 Explain

Pay does not update itself

A student expects this segment to display 120. What does it display, and why?

hoursWorked ← 6
hourlyWage ← 15
pay ← hoursWorked * hourlyWage
hoursWorked ← 8
DISPLAY(pay)
  1. 1
    Line 3 evaluates hoursWorked * hourlyWage with the values at that moment, 6 × 15, and stores a copy of the result in pay.
  2. 2
    Line 4 changes hoursWorked only. pay is not a formula that recalculates; it holds a value.
Answer: It displays 90. To get 120, line 3 must run again after line 4.

8Common mistakes

Common Mistake 1 · Thinking b ← a links the two

It copies the current value. Later changes to a never reach b.

Common Mistake 2 · Reading ← as “equals”

a ← 5 stores 5 in a. a = 5 asks whether a is 5 and gives true or false. Neither one is the other.

Common Mistake 3 · Treating a variable as a formula

total ← price * qty stores a number. If qty changes afterward, total stays the same until the line runs again.

Common Mistake 4 · Using a number for something that is really text

ZIP codes, phone numbers, and IDs keep their leading zeros only as strings.

Explain an assignment like this

“Line 2 evaluates a, which is 1, and stores a copy of 1 in b. Line 3 assigns 2 to a only. A variable holds its most recent value, and b was last assigned 1, so the program displays 1.”

Say what the right side evaluates to, which variable receives the copy, and which assignment was the most recent.