学习目标 2.1.A: 使用书面语言或图表来表示日常生活中涉及选择和重复的模式及算法。
- 2.1.A.1 算法的基本构建模块包括顺序、选择和重复。
- 2.1.A.2 算法可以包含通过决策实现的选择,以及通过循环实现的重复。
- 2.1.A.3 当算法执行路径的选择取决于一个真或假的判断时,就发生了选择。
- 2.1.A.4 重复是指一个过程不断重复,直到达到预期结果为止。
- 2.1.A.5 顺序、选择和重复的使用顺序会影响算法的结果。
AP 计算机科学 A · 知识点 2
7:58
选择与迭代
这里有三个循环。前两个只差一个字符——一个是小于号,一个是小于或等于号。第一个运行十次。第二个运行十一次。…
英语旁白 · 英中内嵌字幕
学习目标 2.1.A: 使用书面语言或图表来表示日常生活中涉及选择和重复的模式及算法。
来源:College Board AP 课程与考试说明
Algorithms 算法 are built from three control structures 控制结构: sequence 顺序 (steps in order), selection 选择 (choosing a path), and iteration 迭代 (repeating steps). This topic covers selection and iteration – the tools that let a program make decisions and loop.

| English | 中文 | 拼音 |
|---|---|---|
| Algorithms/ˈælɡərɪθəmz/ | 算法 | suàn fǎ |
| control structures/kənˈtrəʊl ˈstrʌktʃəz/ | 控制结构 | kòng zhì jié gòu |
| sequence/ˈsiːkwəns/ | 顺序 | shùn xù |
| selection/sɪˈlekʃn/ | 选择 | xuǎn zé |
| iteration/ˌɪtəˈreɪʃn/ | 迭代 | dié dài |
学习目标 2.2.A: 编写代码以使用关系运算符创建布尔表达式,并确定这些表达式的结果。
== 和 != 来比较值,以确定值是否相同。对于基本类型,这会比较实际的基本类型值;对于引用类型,这会比较对象的引用。<、>、<= 和 >= 进行比较,以确定值之间的关系。来源:College Board AP 课程与考试说明
A boolean expression 布尔表达式 evaluates to true or false, using relational operators 关系运算符: == (equal), != (not equal), <, >, <=, >=. Note == compares primitive values 基本类型值 but object references 对象引用 for objects, so use .equals for Strings.
Worked example. With int a = 7, b = 3; and String s = "cat";:
| Expression | Value | Why |
|---|---|---|
a % b == 1 |
true |
7 % 3 is 1 |
a / b >= 2.5 |
false |
7 / 3 is the int 2 |
a != b * 2 |
true |
b * 2 is 6; arithmetic runs before comparing |
s.equals("cat") |
true |
same characters |
s.length() > b |
false |
3 > 3 is false |
A common mistake is = for ==: if (a = 7) does not compile, because = assigns and gives an int, not a boolean.

布尔表达式计算结果为 true 或 false。AND 仅当两个操作数都为真时才为真;切换输入以查看所有四种情况。
| English | 中文 | 拼音 |
|---|---|---|
| boolean expression/ˈbuːlɪən ekˈspreʃn/ | 布尔表达式 | bù ěr biǎo dá shì |
| relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/ | 关系运算符 | guān xì yùn suàn fú |
| primitive values | 基本类型值 | jī běn lèi xíng zhí |
| object references | 对象引用 | duì xiàng yǐn yòng |
学习目标 2.3.A: 使用选择语句开发代码来表示分支逻辑过程,并确定这些过程的结果。
if 语句是一种选择语句,它通过根据布尔表达式的值执行不同的代码段来影响控制流。if 语句)用于在特定条件下需要执行某段代码的情况。在这种情况下,仅当布尔表达式为 true 时才执行其主体部分。if-else 语句)用于存在两段代码的情况:一段在布尔表达式为 true 时执行,另一段在布尔表达式为 false 时执行。在这种情况下,当布尔表达式为 true 时执行 if 的主体部分,当布尔表达式为 false 时执行 else 的主体部分。来源:College Board AP 课程与考试说明
An if statement 条件语句 runs a block 代码块 only when its condition 条件 is true; an optional else gives an alternative:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

Common mistakes.
if: in if (x > 0); { count++; } the block runs every time.if. Below, "Done" prints whatever t is, despite the indentation:if (t > 30)
System.out.println("Hot");
System.out.println("Done");
当条件为真时,if 语句才会执行其代码块;否则它将跳过到 else。拖动分数跨越边界,观察成绩的变化。
| English | 中文 | 拼音 |
|---|---|---|
| if statement/ɪf ˈsteɪtmənt/ | 条件语句 | tiáo jiàn yǔ jù |
| block/blɒk/ | 代码块 | dài mǎ kuài |
| condition/kənˈdɪʃn/ | 条件 | tiáo jiàn |
学习目标 2.4.A: 编写代码来表示嵌套分支逻辑过程,并确定这些过程的结果。
if 语句是指包含在 if、if-else 或 if-else-if 语句内部的 if、if-else 或 if-else-if 语句。if 语句的布尔表达式仅在外部 if 语句的布尔表达式求值为 true 时才会被评估。if-else-if)。多路选择的执行方式是:仅基于第一个求值为 true 的表达式执行一个代码段。如果没有任何表达式求值为 true 且存在尾随的 else 语句,则执行 else 的代码块。来源:College Board AP 课程与考试说明
Placing an if inside another, or chaining with else if, tests several cases in order. Only the first matching branch 分支 runs:
if (g >= 90) grade = 'A';
else if (g >= 80) grade = 'B';
else grade = 'C';
Worked example. The order of the tests matters. This version never gives an 'A':
if (g >= 80) grade = 'B';
else if (g >= 90) grade = 'A'; // never reached for g >= 90
else grade = 'C';
For g = 95 the first test is already true, so 'B' is chosen and the rest is skipped. With ranges, test the narrowest case first (highest mark first), as in the correct version above. If the chain used separate if statements without else, every true test would run and the last one would win.
| English | 中文 | 拼音 |
|---|---|---|
| branch/bræntʃ/ | 分支 | fēn zhī |
学习目标 2.5.A: 编写代码表示复合布尔表达式,并确定这些表达式的结果。
!(非)、&&(与)和 ||(或)用于布尔表达式。如果 a 为 false,则表达式 !a 计算结果为 true;否则计算结果为 false。如果 a 和 b 均为 true,则表达式 a && b 计算结果为 true;否则计算结果为 false。如果 a 为 true、b 为 true 或两者皆是,则表达式 a || b 计算结果为 true;否则计算结果为 false。逻辑运算符的求值优先级顺序为 !(非),然后是 &&(与),最后是 ||(或)。涉及逻辑运算符的表达式将计算出一个布尔值。&& 或 || 的逻辑运算的结果可以通过仅评估第一个布尔表达式来确定时,就会发生短路求值。在这种情况下,不会评估第二个布尔表达式。来源:College Board AP 课程与考试说明
Logical operators 逻辑运算符 combine conditions: && (and – both true), || (or – at least one true), ! (not – reverse). Java uses short-circuit evaluation 短路求值: && stops if the left side is false, and || stops if the left side is true – useful to guard against 防止 errors, e.g. if (n != 0 && total / n > 5).

Worked example. Evaluate !(x > y) || x < 5 && y == 6 for x = 4, y = 6. The order is !, then &&, then ||:
x > y is 4 > 6, false, so !(x > y) is true.x < 5 && y == 6 is true && true, true.true || true is true. In fact, step 2 is never run: || already has true on its left and short-circuits.Short-circuiting changes what runs. In if (s != null && s.length() > 0) the null check must come first; the other order throws a NullPointerException when s is null.
| English | 中文 | 拼音 |
|---|---|---|
| Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/ | 逻辑运算符 | luó jí yùn suàn fú |
| short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/ | 短路求值 | duǎn lù qiú zhí |
| guard against | 防止 | fáng zhǐ |
学习标准 2.6.A: 比较等价的布尔表达式。
!(a && b) 等价于 !a || !b,布尔表达式 !(a || b) 等价于 !a && !b。学习标准 2.6.B: 开发代码使用布尔表达式比较对象引用并确定这些表达式的结果。
== 和 != 比较对象引用。== 或 != 将对象引用与 null 进行比较,以确定该引用是否实际指向一个对象。equals 方法,可用于指定该类两个对象的等价性标准。两个对象的等价性通常通过这两个对象的属性来确定。
equals 方法不在 AP 计算机科学 A 课程和考试范围内。来源:College Board AP 课程与考试说明
De Morgan's laws 德摩根定律 rewrite negations: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Two boolean expressions are equivalent 等价 if they give the same result for every input – a truth table 真值表 proves it. Simplifying conditions this way is a common exam task.
Worked example. Write !(age >= 13 && age <= 19) without the !.
!(age >= 13) || !(age <= 19) (the && becomes ||).!(age >= 13) is age < 13; !(age <= 19) is age > 19.age < 13 || age > 19, every age outside the teens.Check one value of each kind: age = 15 gives false in both; age = 25 gives true in both. A common error is to negate >= as <=: the opposite of >= is <.
a |
b |
!(a && b) |
!a || !b |
|---|---|---|---|
| T | T | F | F |
| T | F | T | T |
| F | T | T | T |
| F | F | T | T |
对每组纯布尔输入比较原式、德摩根改写和未交换运算符的候选式;一次不匹配就是反例。
| English | 中文 | 拼音 |
|---|---|---|
| De Morgan's laws/də ˈmɔːɡənz lɔːz/ | 德摩根定律 | dé mó gēn dìng lǜ |
| equivalent/ɪˈkwɪvələnt/ | 等价 | děng jià |
| truth table/truːθ ˈteɪbl/ | 真值表 | zhēn zhí biǎo |
学习目标 2.7.A: 识别何时需要迭代过程才能达到预期结果。
true,就会持续重复。true 时,会发生无限循环。false,则迭代语句的循环体将不会执行。学习目标 2.7.B: 使用 while 循环开发表示迭代过程的代码,并确定这些过程的结果。
while 循环是迭代语句的一种类型。在 while 循环中,每次循环体迭代之前都会评估布尔表达式,包括第一次迭代。当表达式求值为 true 时,执行循环体。这一过程会一直持续,直到布尔表达式求值为 false,此时迭代终止。来源:College Board AP 课程与考试说明
A while loop 当型循环 repeats while its condition stays true, testing before each pass. You must change something inside so the loop eventually stops, or it becomes an infinite loop 无限循环:

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Worked example. Trace a loop that adds the digits of n = 472:
int n = 472, sum = 0;
while (n > 0) {
sum += n % 10; // last digit
n /= 10; // drop it
}
| Pass | n % 10 |
sum |
n after |
|---|---|---|---|
| 1 | 2 | 2 | 47 |
| 2 | 7 | 9 | 4 |
| 3 | 4 | 13 | 0 |
After pass 3 the test n > 0 is false, so the loop stops with sum = 13. If n started at 0, the body would run zero times: a while loop tests before the first pass.
while 循环在其条件保持为真时重复执行,每次迭代更新其变量。逐步运行以观察平方和的累积过程。
| English | 中文 | 拼音 |
|---|---|---|
| while loop/waɪl luːp/ | 当型循环 | dāng xíng xún huán |
| infinite loop/ˈɪnfɪnət luːp/ | 无限循环 | wú xiàn xún huán |
学习目标 2.8.A: 编写代码,使用 for 循环表示迭代过程并确定这些过程的结果。
for 循环是一种迭代语句。for 循环头部包含三个部分:初始化、布尔表达式和更新。for 循环中,初始化语句仅在第一次评估布尔表达式之前执行一次。被初始化的变量称为 循环控制变量。在循环控制变量初始化后立即评估布尔表达式,随后在每次执行增量语句后再次评估,直到其为 false。在每次迭代中,更新操作在整个循环体执行完毕后、再次评估布尔表达式之前执行。for 循环可以重写为等价的 while 循环(反之亦然)。来源:College Board AP 课程与考试说明
A for loop packs initialization 初始化, condition, and update 更新 into one line – best when you know the count:
for (int i = 0; i < n; i++) {
// runs n times, i = 0..n-1
}
A for and an equivalent while do the same work; be able to convert between them.
Worked example. How many times does this run, and what does it print?
for (int k = 10; k > 0; k -= 3)
System.out.print(k + " ");
k takes the values 10, 7, 4, 1; the next value, $-2$, fails k > 0. So it runs 4 times and prints 10 7 4 1. The equivalent while moves the three parts apart:
int k = 10;
while (k > 0) {
System.out.print(k + " ");
k -= 3;
}
A loop for (int i = a; i < b; i++) runs $b - a$ times; with <= it runs $b - a + 1$ times. A variable declared in the for header, such as k, cannot be used after the loop.


for 循环运行固定次数,其计数器逐步遍历一个范围。观察计数器与累计和每次迭代时的推进过程。
| English | 中文 | 拼音 |
|---|---|---|
| initialization | 初始化 | chū shǐ huà |
| update/ˈʌpdeɪt/ | 更新 | gēng xīn |
学习目标 2.9.A: 为标准和原创算法(不使用数据结构)编写代码,并确定这些算法的结果。
来源:College Board AP 课程与考试说明
Combine loops and conditions to solve real problems – count, sum, find a maximum, or test a property:
int max = arr[0];
for (int k = 1; k < arr.length; k++) {
if (arr[k] > max) max = arr[k];
}
Two integer patterns the exam tests directly use % and /. For a nonnegative integer 整数 n, read its digits 数字位 one at a time by taking n % 10 (the last digit) and then n = n / 10 (drop it). For nonzero d, n % d == 0 tests divisibility 整除性: n is evenly divisible by d. Combine them with a counter 计数器 to find the frequency 频率 with which some criterion 条件标准 is met.
Worked example. Count the numbers from 1 to 20 that are divisible by 3 but not by 2.
int count = 0;
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0 && i % 2 != 0) {
count++;
}
}
The multiples of 3 are 3, 6, 9, 12, 15, 18; the odd ones are 3, 9, 15, so count is 3. The counter starts at 0 before the loop; resetting it inside the loop is a common error.
Standard patterns like a running total 累加和, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.
| English | 中文 | 拼音 |
|---|---|---|
| digits | 数字位 | shù zì wèi |
| integer/ˈɪntɪdʒə/ | 整数 | zhěng shù |
| divisibility | 整除性 | zhěng chú xìng |
| counter/ˈkaʊntə/ | 计数器 | jì shù qì |
| frequency/ˈfriːkwənsi/ | 频率 | pín lǜ |
| criterion/kraɪˈtɪərɪən/ | 条件标准 | tiáo jiàn biāo zhǔn |
| running total | 累加和 | lěi jiā hé |
| flag/flæɡ/ | 标志 | biāo zhì |
学习目标 2.10.A: 编写涉及字符串的标准及原创算法的代码,并确定这些算法的结果。
来源:College Board AP 课程与考试说明
Loop through a string by index 索引 to process each character 字符:
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// count vowels, reverse, check for a substring, ...
}
Typical tasks: count occurrences 出现次数, build a reversed or filtered copy, or test whether one string contains another.
Worked example. Count how many times "ana" occurs in "banana", overlaps included.
String s = "banana", t = "ana";
int count = 0;
for (int i = 0; i <= s.length() - t.length(); i++) {
if (s.substring(i, i + t.length()).equals(t)) {
count++;
}
}
i runs from 0 to $6 - 3 = 3$, checking "ban", "ana", "nan", "ana": count is 2. With i < s.length() instead, substring(4, 7) is past the end and throws a StringIndexOutOfBoundsException.

| English | 中文 | 拼音 |
|---|---|---|
| index/ˈɪndeks/ | 索引 | suǒ yǐn |
| character/ˈkærɪktə/ | 字符 | zì fú |
| occurrences | 出现次数 | chū xiàn cì shù |
学习目标 2.11.A: 编写代码以表示嵌套迭代过程,并确定这些过程的结果。
来源:College Board AP 课程与考试说明
A nested loop 嵌套循环 puts one loop inside another; the inner loop 内层循环 completes fully for each pass of the outer loop 外层循环. If the outer runs $n$ times and the inner $m$ times, the body runs $n\times m$ times – the basis for processing grids 网格 and comparing all pairs.

Worked example. What does this print?
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= r; c++) {
System.out.print(c);
}
System.out.println();
}
r |
c takes |
Line printed |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1, 2 | 12 |
| 3 | 1, 2, 3 | 123 |
The println is inside the outer loop but outside the inner one, so it ends each row.
| English | 中文 | 拼音 |
|---|---|---|
| nested loop/ˈnestɪd luːp/ | 嵌套循环 | qiàn tào xún huán |
| inner loop/ˈɪnə luːp/ | 内层循环 | nèi céng xún huán |
| outer loop/ˈaʊtə luːp/ | 外层循环 | wài céng xún huán |
| grids | 网格 | wǎng gé |
学习目标 2.12.A: 计算语句执行次数并对迭代语句进行非正式的运行时比较。
来源:College Board AP 课程与考试说明
Run-time analysis 运行时间分析 counts how many basic steps an algorithm takes as the input size $n$ grows. Count the executions of the innermost statement: with constant work per iteration, visiting each of $n$ items once is linear 线性 ($n$ steps); two full nested loops of $n$ iterations each are quadratic 平方级 ($n^2$). This informal counting lets you compare two algorithms' efficiency 效率.

Exam skill: for a nested loop, be able to state how many times the inner statement runs in terms of the loop bounds – a frequent multiple-choice question.
Worked example. How many stars does this print?
for (int i = 0; i < 4; i++)
for (int j = 0; j < i; j++)
System.out.print("*");
The inner loop runs i times for each outer i: 0 + 1 + 2 + 3 = 6 stars. When the inner bound is the outer variable, the total is the triangular sum $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ – here $\dfrac{4\times3}{2}=6$ – not the full $n^2=16$ of a rectangular nested loop.
运行时间描述了步骤数量随输入规模 $n$ 的增长方式。增大 $n$,观察线性 $O(n)$ 如何远远领先于二次 $O(n^2)$。
| English | 中文 | 拼音 |
|---|---|---|
| Run-time analysis/rʌn taɪm əˈnæləsɪs/ | 运行时间分析 | yùn xíng shí jiān fēn xī |
| linear/ˈlɪnɪə/ | 线性 | xiàn xìng |
| quadratic/kwɒˈdrætɪk/ | 平方级 | píng fāng jí |
| efficiency/ɪˈfɪʃənsi/ | 效率 | xiào lǜ |
< vs <= deliberately, and watch the first and last iteration of every loop (off-by-one 差一错误 is the classic bug 缺陷).&&, ||, ! and remember short-circuit evaluation (put the null check first).if/else if for ranges, a loop for repetition — and avoid an infinite loop by updating the loop variable 循环变量.| English | 中文 | 拼音 |
|---|---|---|
| boundary conditions | 边界条件 | biān jiè tiáo jiàn |
| off-by-one | 差一错误 | chà yī cuò wù |
| bug/bʌɡ/ | 缺陷 | quē xiàn |
| loop variable | 循环变量 | xún huán biàn liàng |
逐步完成,配合即时检查练习。
正在加载学科…