AP CSP topic 3.1
Variables and Assignments
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.
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?
- (A) x = 7, y = 4
- (B) x = 7, y = 7
- (C) x = 4, y = 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?
- (A) 4
- (B) 14
- (C) 17
- (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?
- (A) a ← b b ← a
- (B) temp ← a a ← b b ← temp
- (C) b ← a a ← b
- (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?
- (A) x
- (B) livesLeft
- (C) variable1
- (D) data
Show answer
(B) livesLeft Descriptive names make code easier to read and maintain.