Variables & Control Structures - Complete Interactive Lesson
Part 1: Core Concepts
🔧 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] |
Some languages enforce types strictly (Java, Rust); others are flexible (Python, JavaScript). AP CSP pseudocode is flexible.
Control Flow: Sequencing, Selection, Iteration
| Construct | Pattern |
|---|---|
| Sequencing | Step 1, then step 2, then step 3. |
| Selection | IF condition THEN ... 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 in (0, 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 |
|---|---|
| Counter | i ← 0; REPEAT n TIMES: i ← i + 1 |
| Accumulator | total ← 0; FOR EACH x: total ← total + x |
| Search | found ← false; FOR EACH x: IF x = target THEN found ← true |
| Filter | result ← []; FOR EACH x: IF condition(x) THEN APPEND(result, x) |
| Max / min | best ← list[0]; FOR EACH x: IF x > best THEN best ← x |
Concept Check 🎯
Selection Patterns
| Pattern | When |
|---|---|
| IF / ELSE | Two branches. |
| IF / ELSE IF / ELSE | Multiple ranked conditions. |
| Guard | Early return on edge case. |
| Lookup | Map a value to an action via a table. |
Iteration Patterns
| Pattern | Use |
|---|---|
| Counted loop | Known number of iterations. |
| Conditional loop | Stop when a condition becomes true / false. |
| List traversal | Process each item. |
| Nested loop | Process pairs (or grid). |
Mini-walkthrough: Find Maximum
best ← scoreList[0] FOR EACH score IN scoreList: IF score > best THEN 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 += → accumulator; result.APPEND → filter; if x > best → max.
- Match selection style to # of branches.
- Nested loops handle 2D / pairs.
AP-Style Application 🎯
Part 4: Connections & Interactions
🔀 Variables & Control Flow
Part 4 of 7 — Connections & Interactions
Variables & Control Connect Across CSP
| Connection | Why |
|---|---|
| Variables ↔ Data | Variables hold data values. |
| Control flow ↔ Algorithms | Algorithms ARE control flow over data. |
| Variables ↔ Procedures | Local variables vs. global state. |
| Control ↔ Events | Event-driven code is control flow triggered externally. |
Concept Check 🎯
Scope Of A Variable
Scope = the part of the program where a variable name is visible.
| Scope | Lifetime |
|---|---|
| Local | Inside a procedure call only. |
| Global | Whole program; persists. |
| Block | Inside an IF / loop block (some languages). |
Why scope matters: tightly scoped variables prevent unrelated code from accidentally reading or modifying them.
Mutability
Some variables can be reassigned (mutable); some cannot (immutable / constant).
| Style | Example |
|---|---|
| Mutable | counter ← counter + 1 |
| Constant | PI ← 3.14159 (never reassigned) |
Constants make intent clear and prevent accidental change.
Side Effects
A side effect = a change to state outside the local scope (writing a file, modifying a global, printing). Functions with no side effects are easier to test and reason about.
Applied Recall ✍️
-
The part of a program where a variable name is visible is called its _______.
-
A variable that exists only inside a procedure is called _______.
-
A change to state outside the local function is called a _______ effect.
Targeted Practice 🔍
AP Exam Strategy: Cross-Topic Variables/Control
- "Why use a local variable?" → encapsulation; doesn't pollute global state.
- "Why a constant?" → intent + safety.
- Event-driven = control flow triggered externally.
AP-Style Application 🎯
Part 5: Change Over Time
🔀 Variables & Control Flow
Part 5 of 7 — Change Over Time
How Programming Languages Handle Variables Has Evolved
| Era | Trend |
|---|---|
| 1970s | Static typing (C, Pascal); declare type up front. |
| 1990s | Dynamic typing (Python, JavaScript); flexibility. |
| 2010s | Type inference + optional types (TypeScript, Rust). |
| 2020s | Stronger compile-time guarantees, immutability by default in many new languages. |
Concept Check 🎯
Static vs. Dynamic Typing
| Style | When type is checked |
|---|---|
| Static | Compile time (C, Java, Rust). |
| Dynamic | Run time (Python, JS). |
| Gradual | Optional annotations (TypeScript, mypy). |
Static = catch errors earlier; Dynamic = faster prototyping; Gradual = mix-and-match.
Concurrency Pressure On Variables
Modern multi-core hardware made shared mutable state risky. New languages (Rust, Go, modern Java) provide tools to make concurrent variable access safer.
AP CSP Pseudocode Style
The AP exam uses simple pseudocode similar to Python in spirit:
count ← 0 FOR EACH item IN list: IF item > 0 THEN count ← count + 1
You won't need to worry about types or memory management on the exam.
Applied Recall ✍️
-
A language that checks types at compile time is _______-typed.
-
A language like Python that checks types at run time is _______-typed.
-
A philosophy where variables don't change after creation is called _______.
Targeted Practice 🔍
AP Exam Strategy: Language Evolution
- Static vs. dynamic typing tradeoffs.
- Immutability + scope tightening = modern best practices.
- AP pseudocode is high-level, English-like.
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 FOR i FROM 1 TO 4: sum ← sum + i
| Iter | i | sum (after) |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
Final sum = 10.
Worked: Conditions
IF score ≥ 90 THEN grade ← "A" ELSE IF score ≥ 80 THEN grade ← "B" ELSE IF score ≥ 70 THEN grade ← "C" ELSE grade ← "F"
For score = 85 → grade = "B".
Worked: Off-By-One Caution
FOR i FROM 1 TO LENGTH(list): PROCESS(list[i])
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.
-
Tracing a loop step by step 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. |
| Scope | Where a variable is visible. |
| Local / global | Inside a procedure / whole program. |
| Constant | Variable that never changes. |
| Off-by-one | A common bug at loop boundaries. |
| Side effect | Change to state outside the local scope. |
Common Pitfalls
- Reading = as equality when it's assignment (or vice versa).
- Off-by-one errors in loops.
- Infinite loops (condition never becomes the exit condition).
- Modifying global state from many places, creating bugs.
- 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.
- Local + constant + pure = modern good practice.
AP-Style Application 🎯