Skip to content
🎯⭐ INTERACTIVE LESSON

Variables & Control Structures

Learn step-by-step with interactive practice!

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)
ConceptPseudocodeMeaning
Assignmentx ← 5Store 5 in variable x
Updatex ← x + 1Add 1 to current value of x
DisplayDISPLAY(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

TypeExamplesOperations
Number42, 3.14, -7+, -, *, /, MOD
String"hello", "123"Concatenation, length
Booleantrue, falseAND, 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

OperatorMeaning
=Equal to
≠Not equal to
>Greater than
<Less than
≥Greater than or equal to
≤Less than or equal to

Boolean Operators

OperatorDescription
ANDTrue only if BOTH are true
ORTrue if at LEAST one is true
NOTReverses 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 ✍️

  1. The assignment operator in AP CSP pseudocode is the _______ arrow (←).

  2. The Boolean operator that returns true only when BOTH conditions are true is _______.

  3. 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.

StatementEffect
score ← 0Create variable score, set to 0.
score ← score + 10Read 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

TypeExample
Integer42, -7
Floating-point3.14, -0.5
Booleantrue, 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

ConstructPattern
SequencingStep 1, then step 2, then step 3.
SelectionIF (condition) { … } ELSE { … }
IterationREPEAT 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.

ExpressionTruth
age ≥ 18true 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 ✍️

  1. A name bound to a value in memory is called a _______.

  2. The three core control structures are sequencing, selection, and _______.

  3. 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

PatternSkeleton (reference sheet pseudocode)
Countercount ← 0, then in the loop: IF (condition) { count ← count + 1 }
Accumulatortotal ← 0, then in the loop: total ← total + x
Searchfound ← false, then in the loop: IF (x = target) { found ← true }
Filterresult ← [], then in the loop: IF (condition) { APPEND(result, x) }
Max / minbest ← list[1], then in the loop: IF (x > best) { best ← x }

Concept Check 🎯

Selection Patterns

PatternWhen
IFDo something only when a condition is true.
IF / ELSETwo branches.
IF nested inside ELSESeveral ranked conditions, checked in order.
GuardRETURN early on an edge case.

Iteration Patterns

PatternUse
REPEAT n TIMESKnown number of iterations.
REPEAT UNTIL (condition)Stop when a condition becomes true.
FOR EACH item IN listProcess each item.
Nested loopProcess 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 ✍️

  1. The pattern total ← total + x inside a loop is called the _______ pattern.

  2. A pattern that produces a NEW list of items meeting a condition is called _______.

  3. 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
    }
}
ageOuter test age < 13Inner test age ≥ 65price
10truenot checked8
13falsefalse12
65falsetrue9

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.

ExpressionEquivalent 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 ✍️

  1. Conditional statements placed inside other conditional statements are called _______ conditionals.

  2. Using the ticket-price code, what is price when age is 65? _______

  3. 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.

ExpressionValueWhy
17 / 53.4/ is ordinary division on the exam
17 MOD 52the remainder when 17 is divided by 5
20 MOD 505 divides 20 evenly
4 MOD 747 goes into 4 zero times, remainder 4
3 + 10 MOD 45MOD first: 10 MOD 4 = 2, then 3 + 2
(3 + 10) MOD 41parentheses 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

GoalExpression
Is n even?n MOD 2 = 0
Is n a multiple of 3?n MOD 3 = 0
Last digit of a whole numbern MOD 10
Cycle through 1 to 7day ← (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 ✍️

  1. 29 MOD 6 evaluates to _______.

  2. Using the concat procedure above, concat("sun", "set") returns _______.

  3. 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     }

Iterisum (after)
111
223
336
4410

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 ✍️

  1. In AP CSP pseudocode, the first element of a list is at index _______.

  2. To swap two variables you need a _______ variable.

  3. 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

TermDefinition
VariableNamed container for a value.
AssignmentSet a variable's value.
BooleanTrue / false.
SequencingSteps in order.
SelectionIF / ELSE.
IterationLoop.
Nested conditionalAn IF inside another IF or ELSE.
MODRemainder after division; same precedence as * and /.
Off-by-oneA 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 ✍️

  1. AP CSP pseudocode lists are _______-indexed.

  2. A loop whose exit condition is never satisfied is called an _______ loop.

  3. 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 🎯