Code below uses the AP CSP pseudocode – the exam's language-neutral reference. Assignment is written a ← expression, and list indices start at 1.
Algorithms and Programming
AP Computer Science Principles · Topic 3
9:10
Algorithms and Programming
Imagine a phone book with a million names, and you must find one. Check them one at a time, and you could be there all day. There is a way to find it in about…
English narration · English + 中文 subtitles burned in
3.1
Variables and Assignments
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-1 | AAP-1.A |
|
AAP-1.B |
|
Source: College Board AP Course and Exam Description
A variable 变量 is a named place that holds a value. The assignment 赋值 operator stores the value on the right into the variable on the left:

a ← 5
b ← a + 3 // b is now 8
A variable holds one value at a time; assigning again replaces it. Variables let a program store input, remember results, and reuse them.
Worked example (a failed swap). What is displayed?
a ← 3
b ← 7
a ← b
b ← a
DISPLAY(a)
DISPLAY(b)
| Line | a |
b |
|---|---|---|
a ← 3 |
3 | – |
b ← 7 |
3 | 7 |
a ← b |
7 | 7 |
b ← a |
7 | 7 |
It displays 7 7: the old value of a was replaced before it was copied. A swap needs a third variable: temp ← a, a ← b, b ← temp.
Watch a variable hold and change its value
A variable is a named box that stores one value at a time. An assignment copies a value into the box; assigning again overwrites whatever was there.
| English |
|---|
| variable/ˈveərɪəbl/ |
| assignment/əˈsaɪnmənt/ |
3.2
Data Abstraction
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-1 | AAP-1.C |
|
AAP-1.D |
|
Source: College Board AP Course and Exam Description
Data abstraction 数据抽象 lets you manage complexity by giving a single name to a collection of data – for example, a list rather than dozens of separate variables. It hides detail: you use the named collection without worrying about how it is stored. Lists (below) are the course's main data abstraction.

| English |
|---|
| Data abstraction/ˈdeɪtə əbˈstrækʃn/ |
3.3
Mathematical Expressions
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.A |
|
AAP-2.B |
| |
AAP-2.C |
|
Source: College Board AP Course and Exam Description
Programs compute with the operators +, -, *, /, and MOD (the remainder 余数 of a division, e.g. 17 MOD 5 is 2). Expressions follow the usual order of operations. MOD is especially useful for testing divisibility (n MOD 2 = 0 means n is even) and for wrapping values around a range.

Worked example. MOD has the same priority as * and /, so it is done before + and -:
| Expression | Steps | Value |
|---|---|---|
17 MOD 5 + 3 * 2 |
2 + 6 |
8 |
(17 + 3) MOD 5 |
20 MOD 5 |
0 |
472 MOD 10 |
remainder after dividing by 10 | 2, the last digit |
(5 + 4) MOD 7 |
day 5 plus 4 days, in a 7-day week | 2 |
3 MOD 8 |
8 goes 0 times, remainder 3 | 3 |
The last two rows show the wrap-around: day numbers 0 to 6 never go past 6. Note that / in AP pseudocode is ordinary division, so 7 / 2 is 3.5.
Evaluate an expression step by step
An expression is evaluated with order of operations: multiplication and division happen before addition and subtraction, left to right.
| English |
|---|
| remainder/rɪˈmeɪndə/ |
3.4
Strings
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.D |
|
Source: College Board AP Course and Exam Description
A string 字符串 is an ordered sequence of characters, like "hello". Programs join strings (concatenation 拼接) and find their length. Strings represent text – names, messages, sequences – and are a common program input and output.

The exam reference sheet has no string procedures, so a question defines the ones it uses, for example concat(str1, str2), which joins two strings, and substring(str, start, length), which returns length characters of str starting at position start.
Worked example. With those definitions and word ← "computer":
substring(word, 4, 3)starts at character 4,p, and takes 3 characters:"put".substring(word, 1, 1)is"c".concat(substring(word, 1, 3), "et")isconcat("com", "et"), which is"comet".
Positions start at 1, so the last character of a string s is at position LENGTH(s); but always read the question's own definition first.
| English |
|---|
| string/strɪŋ/ |
| concatenation/kənˌkætəˈneɪʃn/ |
3.5
Boolean Expressions
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.E |
|
AAP-2.F |
|
Source: College Board AP Course and Exam Description
A Boolean expression 布尔表达式 evaluates to true or false. It uses relational operators (=, ≠, <, >, ≤, ≥) and logical operators NOT, AND, OR:

NOTreverses a value,ANDis true only when both sides are true,ORis true when at least one side is true.
These conditions drive every decision and loop.
Worked example. With age ← 15 and member ← false, evaluate (age ≥ 13 AND age ≤ 19) AND NOT member:
age ≥ 13is true;age ≤ 19is true; so the bracket is true.NOT memberisNOT false, true.true AND trueis true.
p |
q |
p AND q |
p OR q |
NOT p |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
The opposite of x > 5 is x ≤ 5, not x < 5: the value 5 itself belongs to the opposite.
Try the OR truth table
A Boolean expression is either true (1) or false (0). OR is true when at least one input is true; flip the inputs to see every case.
| English |
|---|
| Boolean expression/ˈbuːlɪən ekˈspreʃn/ |
3.6
Conditionals
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.G |
|
AAP-2.H |
|
Source: College Board AP Course and Exam Description
A conditional (selection) 条件语句 chooses which code to run. IF runs a block only when its condition is true; ELSE gives an alternative:

IF (score ≥ 60)
{
DISPLAY("Pass")
}
ELSE
{
DISPLAY("Fail")
}
Worked example. Two separate IFs are not the same as IF … ELSE. For n ← 12:
IF (n > 10)
{
n ← n - 5
}
IF (n < 10)
{
n ← n * 2
}
DISPLAY(n)
The first test is true, so n becomes 7; the second IF then tests the new value, 7 < 10, which is true, so n becomes 14. Written with ELSE, only the first branch would run and the program would display 7.
Follow an if / else decision
A conditional runs one branch or another depending on whether its condition is true. Slide the value across the threshold and watch which branch is taken.
| English |
|---|
| conditional (selection)/kənˈdɪʃənl/ |
3.7
Nested Conditionals
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.I |
|
Source: College Board AP Course and Exam Description
A nested conditional 嵌套条件 places one IF inside another (or chains ELSE IF) to choose among more than two paths. Only the first matching branch runs:
IF (g ≥ 90) { grade ← "A" }
ELSE IF (g ≥ 80) { grade ← "B" }
ELSE { grade ← "C" }

| English |
|---|
| nested conditional/ˈnestɪd kənˈdɪʃənl/ |
3.8
Iteration
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.J |
|
AAP-2.K |
|
Source: College Board AP Course and Exam Description
Iteration (a loop) 迭代 repeats instructions. AP pseudocode has two forms:

REPEAT 5 TIMES // a fixed count
{
DISPLAY("hi")
}
REPEAT UNTIL (found) // until a condition becomes true
{
...
}
A loop that never meets its stopping condition is an infinite loop 无限循环.
REPEAT UNTIL (condition) checks the condition before each pass and stops as soon as it is true; if it is already true at the start, the body runs zero times.
Worked example. What is displayed, and how many times does the body run?
n ← 1
REPEAT UNTIL (n > 20)
{
n ← n * 2
}
DISPLAY(n)
| Pass | n before |
n after |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 | 4 |
| 3 | 4 | 8 |
| 4 | 8 | 16 |
| 5 | 16 | 32 |
After pass 5, n > 20 is true, so the loop stops: the body ran 5 times and the program displays 32. If the body were n ← n * 1, n would stay 1 and the loop would never end.
Trace a loop one pass at a time
A loop repeats a block while its counter runs through a range. Step through to watch the counter and the running total update each pass.
| English |
|---|
| Iteration (a loop)/ˌɪtəˈreɪʃn/ |
| infinite loop/ˈɪnfɪnət luːp/ |
3.9
Developing Algorithms
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.L |
|
AAP-2.M |
|
Source: College Board AP Course and Exam Description
An algorithm is not the same thing as code. Beyond visual and textual programming languages, an algorithm can be expressed in a variety of ways: in natural language (ordinary sentences), as a diagram such as a flowchart, or in pseudocode. Those forms are for people — they let you check the logic and agree on it before any language is chosen, and the same algorithm can then be written in any language.

When you do write it in a programming language, clarity and readability are important considerations, not decoration: meaningful variable names, consistent indentation and comments explaining why rather than what. The program has to be read and modified later by someone — often you — and an algorithm nobody can follow cannot be maintained or debugged.
An algorithm 算法 is a finite sequence of steps that solves a problem, built from sequencing, selection, and iteration. Different algorithms can solve the same problem, and you should be able to combine and modify existing algorithms (for example, count the values in a list that meet a condition, or find the largest). Trace an algorithm by hand to check it is correct.

| English |
|---|
| algorithm/ˈælɡərɪθəm/ |
3.10
Lists
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.N |
|
AAP-2.O |
|
Source: College Board AP Course and Exam Description
A list 列表 is an ordered collection of values under one name, the course's key data abstraction. AP pseudocode indexes from 1:

scores ← [88, 74, 95]
DISPLAY(scores[1]) // 88
scores[2] ← 80 // replace the 2nd value
APPEND(scores, 60) // add to the end
INSERT(scores, 1, 100) // insert at index 1
REMOVE(scores, 3) // delete the 3rd element
LENGTH(scores) // how many elements
Traverse a list with a loop to sum, count, search, or find a maximum:
FOR EACH x IN scores
{
total ← total + x
}
Worked example (tracing a list traversal). This procedure should count the scores of at least 80:
count ← 0
FOR EACH x IN [88, 74, 95, 80]
{
IF (x ≥ 80)
{
count ← count + 1
}
}
DISPLAY(count)
x |
x ≥ 80? |
count after |
|---|---|---|
| 88 | true | 1 |
| 74 | false | 1 |
| 95 | true | 2 |
| 80 | true | 3 |
It displays 3. Two traps the exam sets: delete count ← 0 and count has no starting value, so the result is undefined; write x > 80 and the last score is missed, so it displays 2. Trace the boundary value every time.
| English |
|---|
| list/lɪst/ |
3.11
Binary Search
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-2 | AAP-2.P |
|
Source: College Board AP Course and Exam Description
Binary search 二分搜索 finds a value in a sorted list far faster than checking each element. It looks at the middle element, then discards the half that cannot contain the target, repeating until found. Each step halves the search space, so a list of $n$ items takes about $\log_2 n$ steps. It requires the data to be sorted first.


Worked example. Searching a sorted list of $8$ items, binary search halves the range each step: $8\rightarrow4\rightarrow2\rightarrow1$ in three halvings, and the one item left must still be checked, so at most $4$ comparisons ($\log_2 8+1$), whereas a linear search could take up to $8$. The advantage grows explosively: about $1{,}000$ items need only $\approx10$ binary-search steps (but up to $1{,}000$ linear ones), and $1{,}000{,}000$ items need just $\approx20$. Halving is what makes it a reasonable-time algorithm.
| English |
|---|
| Binary search/ˈbaɪnəri sɜːtʃ/ |
3.12
Calling Procedures
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-3 | AAP-3.A |
|
Source: College Board AP Course and Exam Description
A procedure (function) 过程 is a named, reusable block of code. Calling it runs its code with the arguments you supply, and it may return a value:
sum ← Add(3, 4) // call, passing 3 and 4
Procedures let you use code without knowing its inner workings – procedural abstraction 过程抽象.
Worked example. What is displayed?
PROCEDURE Mystery(x, y)
{
IF (x > y)
{
RETURN(x - y)
}
RETURN(y - x)
}
DISPLAY(Mystery(3, 10))
DISPLAY(Mystery(Mystery(9, 4), 2))
Mystery(3, 10):3 > 10is false, so it returns10 - 3, which is7.- The inner call
Mystery(9, 4)returns5; thenMystery(5, 2)returns3.
It displays 7 3. The procedure returns the distance between two numbers. RETURN ends the procedure at once, so the second RETURN runs only when the IF was false.

| English |
|---|
| procedure (function)/prəˈsiːdʒə/ |
| procedural abstraction/prəˈsiːdʒərəl əbˈstrækʃn/ |
3.13
Developing Procedures
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-3 | AAP-3.B |
|
AAP-3.C |
|
Source: College Board AP Course and Exam Description
You define a procedure with a name, parameters (inputs), and a body, and optionally RETURN a result:

PROCEDURE Add(a, b)
{
RETURN(a + b)
}
Worked example. Write a procedure CountAbove(list, limit) that returns how many values in list are greater than limit.
PROCEDURE CountAbove(list, limit)
{
count ← 0
FOR EACH item IN list
{
IF (item > limit)
{
count ← count + 1
}
}
RETURN(count)
}
CountAbove([4, 9, 12, 7], 6) returns 3. The parameters make it general: the same procedure works for any list and any limit, which is the point of a procedure. Displaying count inside the loop, or forgetting RETURN, are the usual mistakes.
Writing your own procedures reduces repetition, breaks a big problem into named pieces, and makes programs readable and easier to test – the essence of abstraction 抽象.
| English |
|---|
| abstraction/əbˈstrækʃn/ |
3.14
Libraries
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-3 | AAP-3.D |
|
Source: College Board AP Course and Exam Description
A library 库 is a collection of ready-made procedures that others can reuse. An API (Application Program Interface) 应用程序接口 documents what each procedure does, its parameters, and its result – so you can use it without seeing its code. Libraries save time and let you build on existing, tested work.
The documentation is part of the library. Documentation for an API or library is necessary in order to understand the behaviours it provides and how to use them — what each procedure expects as parameters, what it returns, and what it does at the edges. Without it you would have to read the source, which defeats the point of abstraction; with it you can use a procedure correctly without knowing how it works inside.

| English |
|---|
| library/ˈlaɪbrəri/ |
| Interface/ˈɪntəfeɪs/ |
3.15
Random Values
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-3 | AAP-3.E |
|
Source: College Board AP Course and Exam Description
RANDOM(a, b) returns a random integer from a to b (inclusive), letting a program produce unpredictable results – for games, sampling, or simulations. Each call may give a different value, so a program using randomness behaves differently each run.
Worked example. A game gives a prize 30% of the time:
IF (RANDOM(1, 10) ≤ 3)
{
DISPLAY("Prize!")
}
RANDOM(1, 10) has 10 equally likely values; 1, 2 and 3 are 3 of them, so the chance is $\frac{3}{10} = 30\%$. RANDOM(0, 10) ≤ 3 would be wrong: it has 11 values, 4 of them at most 3. To list every possible output of a program with RANDOM, try the smallest and largest values the call can return.

3.16
Simulations
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-3 | AAP-3.F |
|
Source: College Board AP Course and Exam Description
A simulation 模拟 is a program that models a real-world process to study it safely and cheaply. Simulations simplify reality (they leave out detail) and often use randomness to imitate chance events. They let you test scenarios that would be too costly, slow, or dangerous in real life – but their results are only as good as their assumptions.
A simulation is a way of doing science, not just a picture. Because it can be run many times, cheaply and with one variable changed at a time, a simulation facilitates the formulation and refinement of hypotheses about the object or phenomenon under consideration: you propose an explanation, run the model, compare the result with reality, and adjust either the hypothesis or the model. That is why a simulation's simplifications matter — a result only supports a hypothesis about the real world to the extent that what was left out does not matter.

| English |
|---|
| simulation/ˌsɪmjʊˈleɪʃn/ |
3.17
Algorithmic Efficiency
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-4 | AAP-4.A |
|
Source: College Board AP Course and Exam Description
Efficiency 效率 is how much time (or memory) an algorithm needs as its input grows. A reasonable-time algorithm's work grows like a polynomial of the input size (e.g. linear or quadratic); an unreasonable-time algorithm grows far faster (e.g. doubling with each added item), becoming impractical for large inputs. A faster algorithm can make a previously impossible problem solvable. Sometimes an exact answer takes too long, so a heuristic 启发式 – an approach that finds a good-enough answer quickly – is used instead.

| English |
|---|
| Efficiency/ɪˈfɪʃənsi/ |
| heuristic/hjuːˈrɪstɪk/ |
3.18
Undecidable Problems
Syllabus
| Enduring Understanding | Learning Objective | Essential Knowledge |
|---|---|---|
AAP-4 | AAP-4.B |
|
Source: College Board AP Course and Exam Description
Some problems are undecidable 不可判定: no algorithm can solve every case of them with a correct yes/no answer. This is a fundamental limit of computing – not a matter of needing a faster computer, but a proof that no such algorithm can exist.
The best-known example is the halting problem 停机问题: deciding, for any program and its input, whether the program will eventually stop or run for ever. A tool can answer this for many programs, but it has been proved that no algorithm answers it correctly for all of them. An undecidable problem may still be solved for particular cases; what is impossible is one algorithm for every case.
Exam skill: be able to determine a code segment's result by tracing it, compare two algorithms' efficiency (reasonable vs unreasonable time), and recognize procedural and data abstraction in a program.

| English |
|---|
| undecidable/ˌʌndɪˈsaɪdəbl/ |
| halting problem |
3.18
Exam tips
- Know a variable is a named store for a value and trace how assignment updates it step by step.
- Read the AP pseudocode carefully —
a <- expressionassigns, and lists are 1-indexed on the exam reference sheet. - Distinguish a variable from a list (a collection accessed by index) and use list operations correctly.
- Evaluate expressions with the right precedence and boolean logic (
AND,OR,NOT). - Pick clear, meaningful variable names — the written tasks reward readable code.
Interactive lessons on this topic
Work through it step by step, with instant-check exercises.
- Variables and Assignments
- Data Abstraction
- Mathematical Expressions
- Strings
- Boolean Expressions
- Conditionals
- Nested Conditionals
- Iteration
- Developing Algorithms
- Lists
- Binary Search
- Calling Procedures
- Developing Procedures
- Libraries
- Random Values
- Simulations
- Algorithmic Efficiency
- Undecidable Problems