← Back to course

Variables, Assignment & Expressions

You’ll be able to

Variables hold values

A variable is a named location that stores a value the program can use and change. In AP pseudocode, the assignment statement a ← expression first evaluates the expression on the right, then stores the result in the variable on the left. So score ← 10 puts 10 into score, and score ← score + 5 reads the current value (10), adds 5, and stores 15 back — the old value is replaced. Reading a variable does not change it; only an assignment to it does.

Expressions and operators

An expression is any combination of values, variables, and operators that evaluates to a single value. AP pseudocode uses +, , *, / for arithmetic and MOD for the remainder of integer division: 17 MOD 5 is 2, because 17 ÷ 5 is 3 remainder 2. MOD is enormously useful — n MOD 2 is 0 exactly when n is even, and MOD is how you detect divisibility or wrap values around a range. Operators follow standard precedence: *, /, and MOD before + and .

Order matters: tracing assignments

Because assignment replaces a value, the order of statements determines the outcome. To predict what a program does, trace it: make a small table of each variable and update it one statement at a time, exactly as the computer would. Never guess the final values by looking at the whole block at once — a variable may be reassigned several times, and only the sequence of updates reveals the truth. Tracing is the single most important skill for the exam’s code questions.

The MOD operator
a MOD b = the remainder when a is divided by b
Example: 23 MOD 10 = 3. A number n is even exactly when n MOD 2 = 0, and n MOD b = 0 means b divides n evenly.
Worked example

Trace this program and give the final value displayed. x ← 4 y ← 7 x ← x + y y ← x − y DISPLAY(x + y)

  1. 1.Start: x = 4, y = 7.
  2. 2.x ← x + y: x becomes 4 + 7 = 11. Now x = 11, y = 7.
  3. 3.y ← x − y: y becomes 11 − 7 = 4. Now x = 11, y = 4.
  4. 4.DISPLAY(x + y): 11 + 4 = 15.
Answer: The program displays 15. Tracing statement by statement is essential because x and y are each reassigned, so their final values (11 and 4) differ from their starting values.
Checkpoint

After the following runs, what value does `a` hold? `a ← 5` `b ← 3` `a ← b` `b ← 8`

Watch out

Assignment copies a value, it does not link variables. After a ← b, changing b later has no effect on a. Trace each statement in order and never assume a variable keeps its first value.

Checkpoint

What is the value of `29 MOD 6`?

On the exam

MOD returns the remainder, not the quotient. Keep the classic uses ready: n MOD 2 = 0 tests even, and n MOD b = 0 tests whether b divides n evenly.

Answer the 2 checkpoints as you read.

Sign in to save your progress