Variables & Control Structures - Complete Interactive Lesson
Part 1: Variables, Assignments, Conditionals, and Loops
🔧 Variables & Control Structures
Part 1 of 7 — Variables, Assignments, Conditionals, and Loops
Variables and Assignment
In the AP CSP pseudocode:
score ← 0 // Assign 0 to score
name ← "Alice" // Assign "Alice" to name
score ← score + 10 // Update score (now 10)
| Concept | Pseudocode | Meaning |
|---|---|---|
| Assignment | x ← 5 | Store 5 in variable x |
| Update | x ← x + 1 | Add 1 to current value of x |
| Display | DISPLAY(x) | Show value of x on screen |
🔑 The left arrow (←) means "gets the value of." It is NOT an equality check — it is an assignment. The right side is evaluated first, then stored in the left side.
Data Types
| Type | Examples | Operations |
|---|---|---|
| Number | 42, 3.14, -7 | +, -, *, /, MOD |
| String | "hello", "123" | Concatenation, length |
| Boolean | true, false | AND, OR, NOT |
| List | [1, 2, 3] | Access, insert, append, remove |
Concept Check 🎯
Conditionals (Selection)
IF (condition)
{
// Runs if condition is true
}
ELSE
{
// Runs if condition is false
}
Comparison Operators
| Operator | Meaning |
|---|---|
| = | Equal to |
| ≠ | Not equal to |
| > | Greater than |
| < | Less than |
| ≥ | Greater than or equal to |
| ≤ | Less than or equal to |
Boolean Operators
| Operator | Description |
|---|---|
| AND | True only if BOTH are true |
| OR | True if at LEAST one is true |
| NOT | Reverses true/false |
Loops (Iteration)
REPEAT n TIMES
REPEAT 5 TIMES
{
DISPLAY("Hello")
}
// Displays "Hello" five times
REPEAT UNTIL (condition)
x ← 1
REPEAT UNTIL (x > 5)
{
DISPLAY(x)
x ← x + 1
}
// Displays: 1, 2, 3, 4, 5
⚠️ REPEAT UNTIL checks the condition BEFORE each iteration. If the condition is already true, the loop body never executes.
Applied Recall ✍️
-
The assignment operator in AP CSP pseudocode is the _______ arrow (←).
-
The Boolean operator that returns true only when BOTH conditions are true is _______.
-
REPEAT UNTIL checks the condition _______ each iteration (not after).
Evaluate the Expression 🔍
AP Exam Strategy: Variables & Control
- Trace code carefully — write down variable values after each line
- Assignment (←) is NOT equality — the right side is evaluated first
- Know De Morgan: NOT(A AND B) = NOT A OR NOT B; NOT(A OR B) = NOT A AND NOT B
- REPEAT UNTIL is like a while loop that continues UNTIL the condition becomes true (opposite of while)
- Every IF needs a corresponding condition; nested IFs test conditions in order
- Swapping two variables requires a temp variable: temp ← a, a ← b, b ← temp
AP-Style Application 🎯
Part 2: Key Processes
🔀 Variables & Control Flow
Part 2 of 7 — Key Processes
Variables Are Named Containers For Values
A variable is a name bound to a value in memory. Programs use variables to store, retrieve, and update information as they run.
| Statement | Effect |
|---|---|
| score ← 0 | Create variable score, set to 0. |
| score ← score + 10 | Read current score, add 10, store back. |
| name ← "Alex" | Bind a string to name. |
The arrow ← (or = in many languages) is assignment, not equality.
Concept Check 🎯
Data Types A Variable Can Hold
| Type | Example |
|---|---|
| Integer | 42, -7 |
| Floating-point | 3.14, -0.5 |
| Boolean | true, false |
| String | "hello" |
| List | [1, 2, 3] |
AP pseudocode does not declare types: the same variable can be assigned a number, a string, a Boolean, or a list.
Control Flow: Sequencing, Selection, Iteration
| Construct | Pattern |
|---|---|
| Sequencing | Step 1, then step 2, then step 3. |
| Selection | IF (condition) { … } ELSE { … } |
| Iteration | REPEAT n TIMES { … } or REPEAT UNTIL (condition) { … } |
Every algorithm in AP CSP can be expressed using just these three building blocks.
Boolean Logic
Conditions evaluate to true or false. Combine with AND / OR / NOT.
| Expression | Truth |
|---|---|
| age ≥ 18 | true if age is at least 18 |
| NOT (x = 0) | true if x is not 0 |
| (a > 0) AND (a < 100) | true if a is strictly between 0 and 100 |
| (role = "admin") OR (role = "owner") | true if either |
Short Walk-through
total ← 0
FOR EACH grade IN gradeList
{
total ← total + grade
}
average ← total / LENGTH(gradeList)
This computes the average using sequencing + iteration + variables.
Applied Recall ✍️
-
A name bound to a value in memory is called a _______.
-
The three core control structures are sequencing, selection, and _______.
-
A condition that evaluates to true or false is called a _______ expression.
Targeted Practice 🔍
AP Exam Strategy: Variables & Control
- "What is x after these statements?" — trace step-by-step; assignment is left ← right.
- "Which loop fits?" — fixed count = REPEAT n TIMES; condition = REPEAT UNTIL; list = FOR EACH.
- "Compound condition" — AND requires both; OR requires either.
AP-Style Application 🎯
Part 3: Patterns & Examples
🔀 Variables & Control Flow
Part 3 of 7 — Patterns & Examples
Common Control-Flow Patterns
| Pattern | Skeleton (reference sheet pseudocode) |
|---|---|
| Counter | count ← 0, then in the loop: IF (condition) { count ← count + 1 } |
| Accumulator | total ← 0, then in the loop: total ← total + x |
| Search | found ← false, then in the loop: IF (x = target) { found ← true } |
| Filter | result ← [], then in the loop: IF (condition) { APPEND(result, x) } |
| Max / min | best ← list[1], then in the loop: IF (x > best) { best ← x } |
Concept Check 🎯
Selection Patterns
| Pattern | When |
|---|---|
| IF | Do something only when a condition is true. |
| IF / ELSE | Two branches. |
| IF nested inside ELSE | Several ranked conditions, checked in order. |
| Guard | RETURN early on an edge case. |
Iteration Patterns
| Pattern | Use |
|---|---|
| REPEAT n TIMES | Known number of iterations. |
| REPEAT UNTIL (condition) | Stop when a condition becomes true. |
| FOR EACH item IN list | Process each item. |
| Nested loop | Process every pair of items. |
Mini-walkthrough: Find Maximum
best ← scoreList[1]
FOR EACH score IN scoreList
{
IF (score > best)
{
best ← score
}
}
Initialize, then update on each item — the canonical pattern for "best so far".
Applied Recall ✍️
-
The pattern total ← total + x inside a loop is called the _______ pattern.
-
A pattern that produces a NEW list of items meeting a condition is called _______.
-
A pattern that finds the largest value in a list is called _______.
Targeted Practice 🔍
AP Exam Strategy: Patterns
- Recognize the loop pattern from the body: total ← total + x → accumulator; APPEND(result, x) inside an IF → filter; IF (x > best) { best ← x } → max.
- Match the selection structure to the number of branches; ranked choices use an IF nested inside an ELSE.
- Nested loops handle pairs of elements.
AP-Style Application 🎯
Part 4: Nested Conditionals and Equivalent Conditions
🔀 Variables & Control Flow
Part 4 of 7 — Nested Conditionals and Equivalent Conditions
Conditionals Inside Conditionals
Nested conditional statements are conditional statements placed inside other conditional statements. The reference sheet has only IF and IF / ELSE, so a choice among three or more ranked cases is written as an IF nested inside an ELSE.
IF (age < 13)
{
price ← 8
}
ELSE
{
IF (age ≥ 65)
{
price ← 9
}
ELSE
{
price ← 12
}
}
| age | Outer test age < 13 | Inner test age ≥ 65 | price |
|---|---|---|---|
| 10 | true | not checked | 8 |
| 13 | false | false | 12 |
| 65 | false | true | 9 |
Trace from the outside in: the inner IF runs only when the outer condition sends control into the ELSE.
Concept Check 🎯
Equivalent Boolean Expressions
Two Boolean expressions are equivalent when they give the same result for every possible input. The exam often asks which condition could replace another without changing a program's behavior.
| Expression | Equivalent expression |
|---|---|
| NOT (x > 5) | x ≤ 5 |
| NOT (a AND b) | (NOT a) OR (NOT b) |
| NOT (a OR b) | (NOT a) AND (NOT b) |
| (x ≥ 1) AND (x ≤ 10) | NOT ((x < 1) OR (x > 10)) |
A Nested IF Can Act Like AND
IF (hasTicket)
{
IF (age ≥ 18)
{
DISPLAY("enter")
}
}
This displays "enter" exactly when hasTicket AND (age ≥ 18) is true, so it is equivalent to a single IF with that combined condition. Once ELSE blocks are added, check each branch separately: the two forms may no longer match.
Checking Equivalence With Boundary Values
Test values on each side of every boundary. To tell x > 5 apart from x ≥ 5, the only value that matters is x = 5: the first is false there, and the second is true.
Applied Recall ✍️
-
Conditional statements placed inside other conditional statements are called _______ conditionals.
-
Using the ticket-price code, what is price when age is 65? _______
-
NOT (a AND b) has the same value as (NOT a) _______ (NOT b).
Targeted Practice 🔍
AP Exam Strategy: Nested Conditionals
- Trace from the outermost IF inward; exactly one innermost branch runs for each input.
- Mark which inputs reach each branch, especially the boundary values (13 vs 12, 65 vs 64).
- Use De Morgan's laws to rewrite NOT applied to AND / OR.
- To check whether two conditions are equivalent, test values on and next to every boundary.
AP-Style Application 🎯
Part 5: Expressions, MOD, and Strings
🔀 Variables & Control Flow
Part 5 of 7 — Expressions, MOD, and Strings
Evaluating Expressions
An expression can be a value, a variable, an operator, or a procedure call that returns a value. Every expression is evaluated to a single value, following the order of operations from mathematics. MOD has the same precedence as * and /, and operators of equal precedence are evaluated left to right.
| Expression | Value | Why |
|---|---|---|
| 17 / 5 | 3.4 | / is ordinary division on the exam |
| 17 MOD 5 | 2 | the remainder when 17 is divided by 5 |
| 20 MOD 5 | 0 | 5 divides 20 evenly |
| 4 MOD 7 | 4 | 7 goes into 4 zero times, remainder 4 |
| 3 + 10 MOD 4 | 5 | MOD first: 10 MOD 4 = 2, then 3 + 2 |
| (3 + 10) MOD 4 | 1 | parentheses first: 13 MOD 4 = 1 |
On the exam, a MOD b is used only with a ≥ 0 and b > 0.
Concept Check 🎯
Common Uses of MOD
| Goal | Expression |
|---|---|
| Is n even? | n MOD 2 = 0 |
| Is n a multiple of 3? | n MOD 3 = 0 |
| Last digit of a whole number | n MOD 10 |
| Cycle through 1 to 7 | day ← (day MOD 7) + 1 |
Strings
A string is an ordered sequence of characters. String concatenation joins two or more strings end to end to make a new string. A substring is part of an existing string. The reference sheet has no string operators, so an exam question defines the procedures it uses. For example:
- concat(str1, str2) returns str1 followed by str2.
- substring(str, start, length) returns length characters of str, beginning at position start (positions start at 1).
word ← "data"
result ← concat(word, "base")
DISPLAY(result) // database
part ← substring(result, 5, 4)
DISPLAY(part) // base
Choosing a Type
Some values are better represented with one type than another: a ZIP code such as "02134" as a string (so the leading 0 is kept), a count as a number, a yes/no fact as a Boolean, and many related values as a list.
Applied Recall ✍️
-
29 MOD 6 evaluates to _______.
-
Using the concat procedure above, concat("sun", "set") returns _______.
-
Using the substring procedure above, substring("planet", 3, 4) returns _______.
Targeted Practice 🔍
AP Exam Strategy: Expressions
- Apply the order of operations: parentheses, then *, /, and MOD from left to right, then + and −.
- a MOD b is always between 0 and b − 1, and a MOD b = 0 means b divides a evenly.
- 17 / 5 is 3.4 on the exam; use MOD for remainders.
- For string questions, read the procedure definitions in the question carefully, then count character positions starting at 1.
AP-Style Application 🎯
Part 6: Problem-Solving Workshop
🔀 Variables & Control Flow
Part 6 of 7 — Problem-Solving Workshop
Variables & Control Workshop
Trace and design with vocabulary in hand.
Concept Check 🎯
Worked: Trace A Loop
sum ← 0 i ← 1 REPEAT 4 TIMES { sum ← sum + i i ← i + 1 }
| Iter | i | sum (after) |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
Final sum = 10.
Worked: Conditions
The reference sheet has only IF and IF / ELSE, so ranked grade bands nest each IF inside the previous ELSE:
IF (score ≥ 90)
{
grade ← "A"
}
ELSE
{
IF (score ≥ 80)
{
grade ← "B"
}
ELSE
{
IF (score ≥ 70)
{
grade ← "C"
}
ELSE
{
grade ← "F"
}
}
}
For score = 85 → grade = "B".
Worked: Off-By-One Caution
i ← 1 REPEAT UNTIL (i > LENGTH(list)) { DISPLAY(list[i]) i ← i + 1 }
In a 1-indexed list this is fine; in a 0-indexed language, you'd need 0 to LENGTH(list) - 1. AP pseudocode is 1-indexed.
Applied Recall ✍️
-
In AP CSP pseudocode, the first element of a list is at index _______.
-
To swap two variables you need a _______ variable.
-
Stepping through a loop by hand and recording each variable's value is called _______.
Targeted Practice 🔍
AP Exam Strategy: Workshop Style
- Trace by drawing a small table of variables across iterations.
- Watch for off-by-one and infinite-loop traps.
- AP pseudocode is 1-indexed.
AP-Style Application 🎯
Part 7: AP Review
🔀 Variables & Control Flow
Part 7 of 7 — AP Review
AP Exam Recap — Variables & Control Flow
Final review.
Concept Check 🎯
Final Vocab
| Term | Definition |
|---|---|
| Variable | Named container for a value. |
| Assignment | Set a variable's value. |
| Boolean | True / false. |
| Sequencing | Steps in order. |
| Selection | IF / ELSE. |
| Iteration | Loop. |
| Nested conditional | An IF inside another IF or ELSE. |
| MOD | Remainder after division; same precedence as * and /. |
| Off-by-one | A common bug at loop boundaries. |
Common Pitfalls
- Reading ← as a comparison, or = as an assignment (← assigns; = compares).
- Off-by-one errors in loops.
- Infinite loops (condition never becomes the exit condition).
- Forgetting that MOD is evaluated before + and −.
- Forgetting that AP pseudocode is 1-indexed.
Applied Recall ✍️
-
AP CSP pseudocode lists are _______-indexed.
-
A loop whose exit condition is never satisfied is called an _______ loop.
-
A bug where a loop runs one too many or one too few times is an _______-by-one error.
Targeted Practice 🔍
Final Exam Tips
- Trace tables are your friend.
- Distinguish counter / accumulator / search / filter / max patterns.
- Watch for off-by-one and infinite loops.
- Rewrite NOT applied to AND / OR with De Morgan's laws, then check a boundary value.
AP-Style Application 🎯