AP Computer Science Principles • Algorithms and Programming

Variables and Assignments

Understanding how programs store, update, and reference data through named abstractions.

Computer science principles illustration with a network, database, and code file
Inside this lesson 9 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

The concept of a variable in computing traces its lineage from mathematics, where letters have long served as placeholders for unknown quantities, into the realm of machine instructions, where physical memory locations store binary data. Early programmers had to reference raw memory addresses—hexadecimal numbers like 0x3A7F—to read and write data. This was error-prone and nearly impossible to maintain as programs grew. The invention of symbolic variable names was one of the most important abstractions in the history of computing, allowing humans to reason about programs in terms of meaningful names rather than opaque addresses.

1840s • Ada Lovelace's Notes

Ada Lovelace described how Charles Babbage's Analytical Engine could store intermediate results in numbered "variables," foreshadowing modern assignment.

1957 • FORTRAN Introduces Named Variables

IBM's FORTRAN compiler allowed programmers to use symbolic names like TOTAL and RATE instead of memory addresses, dramatically improving readability.

1972 • C Language and Typed Variables

Dennis Ritchie's C language formalized variables with explicit data types (int, float, char), influencing decades of language design.

1991 • Python and Dynamic Typing

Guido van Rossum released Python, where variables are dynamically typed—names bind to objects at runtime without explicit type declarations.

The central question that variables and assignments address is deceptively simple: how does a program remember information so it can be used and modified later? Without this mechanism, every computation would be ephemeral—results would vanish the instant they were produced, and no algorithm could build upon prior steps. The AP Computer Science Principles exam treats variables as a foundational abstraction that underpins every algorithm, from simple arithmetic to complex simulations.

SECTION 2

Core Principles & Definitions

At its core, a variable is an abstraction inside a program that holds a value. You can think of it as a named container: the name lets you refer to the stored data, and the data itself can change over time as the program executes. An assignment statement is the operation that places a value into a variable. In most languages—and in the AP CSP pseudocode—this is written with an arrow or equals sign: x ← 5 or x = 5. After this statement executes, the name x refers to the value 5, and any subsequent use of x in an expression will evaluate to 5—until a new assignment changes it.

1

Variable

A named abstraction that stores a single value at any given time. The value can be a number, string, Boolean, or list.
2

Assignment (←)

The operation that stores a value into a variable. The right side is evaluated first, then the result is placed into the variable on the left.
3

Expression

A combination of values, variables, and operators that evaluates to a single result. Expressions appear on the right side of assignment statements.
4

Overwriting / Updating

When a variable is assigned a new value, the old value is permanently replaced. There is no undo—previous data is lost unless saved elsewhere.

SECTION 3

Visual Explanation: How Assignment Works

Assignment Execution: Step by StepStep 1:x ← 7x7Step 2:y ← x + 3x7y10← 7 + 3Step 3:x ← x + 1x8y10← 7 + 1 (old x)y unchanged!Key Insight:In Step 3, x changes to 8, but y remains 10. Assignment copies a value at the momentit executes—it does NOT create a lasting link between variables.Final State:x = 8y = 10Changing x after y was assigned does NOT retroactively change y.
This diagram traces three sequential assignment statements. Notice that in Step 3, when x is updated from 7 to 8, the variable y is not affected because it received its value in Step 2 and has no ongoing connection to x.

The diagram above illustrates a critical concept that the AP CSP exam frequently tests: assignment copies a snapshot of the value at the moment the statement executes. It does not create a formula or live relationship between variables. When you write y ← x + 3, the computer evaluates x + 3 right now, stores the result in y, and moves on. Future changes to x have no retroactive effect on y. This differs fundamentally from mathematical equations, where y = x + 3 expresses a permanent relationship.

SECTION 4

How Assignment Works Under the Hood

The Assignment Operator in AP CSP Pseudocode

The College Board's AP CSP reference sheet uses the left-arrow notation for assignment. This notation makes the direction of data flow explicit: the expression on the right side is evaluated first, and the resulting value flows leftward into the variable. This two-phase process—evaluate, then store—is the key to understanding every assignment statement.

ASSIGNMENT SYNTAX (AP CSP PSEUDOCODE)

variable←expressionvariable ← expression

variable = the name receiving the value; expression = any combination of values, variables, and operators that produces a single result. The expression is fully evaluated before the result is stored.

Self-Referencing Assignments

One of the most common patterns—and a frequent source of exam questions—is a statement where the same variable appears on both sides, such as count ← count + 1. In mathematics, count = count + 1 is a contradiction with no solution. In programming, however, the rule is always evaluate the right side first. The computer reads the current value of count, adds 1, then stores the new result back into count, overwriting the old value. This is the standard pattern for incrementing a counter or accumulating a running total.

SELF-REFERENCING PATTERN

count←count+1count ← count + 1

If count currently holds 4, the right side evaluates to 4 + 1 = 5, and then 5 is stored into count. The old value 4 is permanently lost.

Swapping Two Variables

A classic problem that reveals the importance of assignment order is swapping the values of two variables. If a holds 3 and b holds 7, you cannot simply write a ← b followed by b ← a, because after the first statement both variables hold 7 and the original value of a is lost. The solution requires a temporary variable to preserve the value that would otherwise be overwritten: temp ← a, a ← b, b ← temp. This three-step pattern is a staple of AP CSP exam questions.

SECTION 5

Types of Data Stored in Variables

Variables in AP CSP can store several types of data. While the exam does not require you to declare types explicitly—its pseudocode is dynamically typed—you must understand the distinctions between numbers, strings, Booleans, and lists because the type of data determines which operations are valid. Adding two numbers produces a sum, but "adding" two strings concatenates them—very different behaviors triggered by the same operator.

Data Types Stored in AP CSP VariablesNUMBERscore ← 95pi ← 3.14Integers &decimalsSTRINGname ← "Ada"msg ← "Hi!"Text inquotation marksBOOLEANdone ← trueok ← falseOnly two values:true or falseLISTnums ← [3,7,1]colors ← ["r"]Ordered collectionof valuesReassignment Across Typesx ← 42x holds a numberx ← "hello"x now holds a string (42 is gone)x ← truex now holds a Boolean ("hello" is gone)In AP CSP pseudocode, a variable can hold any type and can change types via reassignment.
Four data types recognized in AP CSP. The lower panel shows that a single variable can be reassigned to hold different types across successive statements—each new assignment completely replaces the old value.
Data TypeExample ValueCommon Operations
Number (integer or decimal)42, 3.14Arithmetic (+, −, ×, /, MOD), comparisons (<, >, =)
String"hello"Concatenation, length, substring extraction
Booleantrue, falseAND, OR, NOT; used in conditionals and loops
List[1, 2, 3]Index access, APPEND, INSERT, REMOVE, LENGTH

Summary of AP CSP data types and their operations

SECTION 6

Worked Example: Tracing Variable State

The most important skill for the AP CSP exam regarding variables is tracing—manually executing code line by line and tracking the value stored in each variable after every statement. Let us trace through a complete example.

ℹ
CODE TO TRACE

Worked example

  1. 1

    Step 1 — Execute Line 1: a ← 5

    The literal value 5 is stored into variable a. Variable b has not been assigned yet.
    a = 5, b = undefined
  2. 2

    Step 2 — Execute Line 2: b ← a × 2

    Evaluate the right side: the current value of a is 5, so 5 × 2 = 10. Store 10 into b.
    a = 5, b = 10
  3. 3

    Step 3 — Execute Line 3: a ← a + b

    Evaluate the right side using current values: a is 5 and b is 10, so 5 + 10 = 15. Store 15 into a, overwriting the old value of 5.
    a = 15, b = 10
  4. 4

    Step 4 — Execute Line 4: b ← a − 3

    Evaluate: a is now 15 (not 5!), so 15 − 3 = 12. Store 12 into b, overwriting 10.
    a = 15, b = 12
  5. 5

    Step 5 — Execute Lines 5–6: DISPLAY

    Line 5 displays the current value of a, which is 15. Line 6 displays the current value of b, which is 12.
    Output: 15 12

SECTION 7

Common Pitfalls & Best Practices

PitfallWhy It HappensCorrect Approach
Treating ← as a math equationStudents read x ← x + 1 as "x equals x + 1" and see a contradictionRead ← as "gets" or "receives." Right side evaluates first, then the result overwrites the left.
Forgetting order mattersStudents assume a ← b and b ← a can swap values without a temp variableUse a temporary variable: temp ← a, a ← b, b ← temp.
Assuming variables stay linkedAfter y ← x, students think changing x will also change yAssignment copies a snapshot. After y ← x, y and x are independent.
Using a variable before assigning itStudents reference a name that has never received a valueAlways initialize variables before using them in expressions.

Common mistakes with variables and how to avoid them

SECTION 8

Connection to Advanced Concepts

Variables and assignments form the foundation for nearly every other topic in AP CSP. Understanding how data is stored and updated is prerequisite to working with iteration (loops depend on counter variables and accumulators), selection (conditionals test Boolean variables), procedures (parameters are assigned when functions are called), and lists (a list is just a variable that holds multiple indexed values).

This Lesson's ConceptAdvanced Extension
Single variable assignmentIteration: a loop variable is reassigned each time the loop body executes
Self-referencing (x ← x + 1)Accumulators in loops: summing or counting elements in a list
Temporary variable for swapSorting algorithms (e.g., Bubble Sort) rely on repeated swaps
Boolean variableFlag variables that control conditional branches and loop termination
Variable scope (conceptual)Local vs. global variables in procedures; parameter passing

How variables and assignments connect to later AP CSP topics

Beyond the AP exam, the concept of assignment extends into paradigms like functional programming, where immutable bindings replace mutable variables, and concurrent programming, where multiple threads accessing the same variable simultaneously can produce race conditions. Understanding the simple model of sequential assignment is the essential first step toward reasoning about these more complex scenarios.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Consider the following code segment: x ← 10 y ← x x ← 20 What is the value of y after these statements execute?
  • A. 20
  • B. 30
  • C. 10
  • D. 0
Show answer (C)
The correct answer is C: 10. When y ← x executes, x currently holds 10, so 10 is copied into y. The subsequent reassignment of x to 20 does not affect y, because assignment copies a snapshot, not a reference. A is wrong (20) because it incorrectly assumes y tracks x's future changes. B is wrong (30) because there is no addition. D is wrong (0) because y was successfully assigned 10.

Question 2: BASIC CALCULATION

What is the value of result after the following code executes? a ← 3 b ← 4 result ← a × b + a
  • A. 12
  • B. 15
  • C. 21
  • D. 7
Show answer (B)
The correct answer is B: 15. The expression on the right side is evaluated using standard order of operations: a × b = 3 × 4 = 12, then 12 + a = 12 + 3 = 15. A (12) is wrong because it omits the + a term. C (21) would result from computing (a × b + a) as a × (b + a) = 3 × 7, which misapplies order of operations. D (7) incorrectly computes a + b rather than the given expression.

Question 3: INTERMEDIATE

Consider this code segment: p ← 2 q ← 5 p ← p + q q ← p − q Which TWO of the following statements are true after the code executes? (Select two.)
  • A. p has the value 7
  • B. q still has the value 5
  • C. q now holds the original value of p
  • D. p and q hold the same value
Show answer (A,C)
The correct answers are A and C. After line 3: p = 2 + 5 = 7. After line 4: q = 7 − 5 = 2. So p = 7 (A is true) and q = 2 which equals p's original value (C is true). B is wrong because q is 2, not 5. D is wrong because p (7) does not equal q (2); they are not equal.

Question 4: APPLIED

A programmer wants to swap the values of two variables first and second without using a third variable. They propose using arithmetic: first ← first + second second ← first − second first ← first − second Trace this code with first = 8 and second = 3. Show the value of each variable after every line. Does this approach successfully swap the values? Explain one limitation of this approach compared to using a temporary variable.
Show answer
Trace (1 point): After line 1: first = 8 + 3 = 11, second = 3. After line 2: first = 11, second = 11 − 3 = 8. After line 3: first = 11 − 8 = 3, second = 8. Conclusion (1 point): Yes, the values are successfully swapped—first is now 3 and second is now 8. Limitation (1 point): This only works for numeric variables. If first and second held strings or lists, the + and − operators would not perform a valid swap. The temporary-variable approach works for any data type.

Question 5: CRITICAL THINKING

A student writes the following code to compute the average of three test scores and determine whether the student passed (average ≥ 70): s1 ← 85 s2 ← 62 s3 ← 78 avg ← s1 + s2 + s3 / 3 passed ← avg ≥ 70 (a) Trace the code and determine the values of avg and passed. (b) Identify the bug and explain why it produces an incorrect result. (c) Write corrected code that computes the average properly. (d) Explain what type of value is stored in the variable passed and why that type is appropriate here.
Show answer
(a) Trace (1 point): Due to order of operations, s3 / 3 is evaluated first: 78 / 3 = 26. Then avg = 85 + 62 + 26 = 173. Since 173 ≥ 70 is true, passed = true. (b) Bug identification (1 point): The division by 3 applies only to s3 due to operator precedence. The programmer intended to divide the entire sum by 3, but wrote s1 + s2 + s3 / 3 instead of (s1 + s2 + s3) / 3. This produces 173 instead of the correct average of 75. (c) Corrected code (1 point): avg ← (s1 + s2 + s3) / 3. This yields (85 + 62 + 78) / 3 = 225 / 3 = 75. With the fix, passed = 75 ≥ 70 = true (the result happens to be the same in this case, but for different inputs the bug could cause incorrect results). (d) Data type explanation (1 point): The variable passed stores a Boolean value (true or false). This is appropriate because the question "did the student pass?" has exactly two possible answers, which maps directly to the Boolean data type. The comparison operator ≥ evaluates to a Boolean, and that result is assigned to passed.

Varsity Tutors • AP Computer Science Principles • Variables and Assignments