AP CSP
AP Computer Science Principles / All lessons / Big Idea 3: Algorithms and Programming
3Big Idea 3: Algorithms and Programming
AP CSP topic 3.1

Variables and Assignments

1011

A variable is a named place to store a value that a program can change later. In AP pseudocode, the arrow assigns a value: score ← 10 stores 10 in score. Assignment replaces the old value, and the right side is calculated first, so score ← score + 1 adds one to the current score. Good variable names describe what they hold, which makes code easier to read.

Picture itscore ← 55scorescore ← score + 38scorescore ← 00score
A variable is a named box that holds one value. Assigning a new value replaces the old one.

Variables and Assignments vocabulary

  • Variable: A named storage location for a value that can change while the program runs.
  • Assignment: Storing a value in a variable, written with ← in AP pseudocode.
  • Data type: The kind of value stored, such as a number, a string, or a Boolean.
  • Boolean: A value that is either true or false.

AP-style practice questions

Try each one, then open the answer. To save your progress, take this quiz in the interactive course.

Skill: Code Analysis
x ← 4
y ← 7
x ← y
y ← x

1. What are the values of x and y after the code runs?

  1. (A) x = 7, y = 4
  2. (B) x = 7, y = 7
  3. (C) x = 4, y = 4
  4. (D) x = 4, y = 7
Show answer

(B) x = 7, y = 7 x becomes 7, then y is set to x, which is now 7.

Skill: Code Analysis
count ← 10
count ← count - 3
count ← count * 2

2. What is the value of count after the code runs?

  1. (A) 4
  2. (B) 14
  3. (C) 17
  4. (D) 20
Show answer

(B) 14 10 - 3 = 7, then 7 * 2 = 14.

Skill: Algorithms and Program Development

3. A programmer wants to swap the values stored in a and b. Which code segment does this correctly?

  1. (A) a ← b b ← a
  2. (B) temp ← a a ← b b ← temp
  3. (C) b ← a a ← b
  4. (D) a ← a + b
Show answer

(B) temp ← a a ← b b ← temp A temporary variable saves a's value before it is overwritten.

Skill: Abstraction in Program Development

4. Which of the following is the best name for a variable that stores the number of lives a player has left?

  1. (A) x
  2. (B) livesLeft
  3. (C) variable1
  4. (D) data
Show answer

(B) livesLeft Descriptive names make code easier to read and maintain.

Open 3.1 in the interactive course