跳到主要内容

选择与迭代

AP 计算机科学 A · 知识点 2

本主题的视频课程 打开视频页面
7:58

选择与迭代

这里有三个循环。前两个只差一个字符——一个是小于号,一个是小于或等于号。第一个运行十次。第二个运行十一次。…

英语旁白 · 英中内嵌字幕

2.1

带选择与重复的算法

教学大纲

学习目标 2.1.A: 使用书面语言或图表来表示日常生活中涉及选择和重复的模式及算法。

  • 2.1.A.1 算法的基本构建模块包括顺序、选择和重复。
  • 2.1.A.2 算法可以包含通过决策实现的选择,以及通过循环实现的重复。
  • 2.1.A.3 当算法执行路径的选择取决于一个真或假的判断时,就发生了选择。
  • 2.1.A.4 重复是指一个过程不断重复,直到达到预期结果为止。
  • 2.1.A.5 顺序、选择和重复的使用顺序会影响算法的结果。

来源:College Board AP 课程与考试说明

English
A flowchart with a decision diamond: selection chooses which path the algorithm takes
A flowchart with a decision diamond: selection chooses which path the algorithm takes

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.

The three control structures: sequence, selection, and iteration
The three control structures: sequence, selection, and iteration
词汇 训练
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

布尔表达式

教学大纲

学习目标 2.2.A: 编写代码以使用关系运算符创建布尔表达式,并确定这些表达式的结果。

  • 2.2.A.1 可以使用 关系运算符 == 和 != 来比较值,以确定值是否相同。对于基本类型,这会比较实际的基本类型值;对于引用类型,这会比较对象的引用。
  • 2.2.A.2 数值可以使用关系运算符 <、>、<= 和 >= 进行比较,以确定值之间的关系。
  • 2.2.A.3 涉及关系运算符的表达式求值结果为布尔值。

来源:College Board AP 课程与考试说明

English
Logic gates & the half-adder

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.

The three families of operators: arithmetic, relational, and logical
The three families of operators: arithmetic, relational, and logical
探索

探索 AND 真值表

布尔表达式计算结果为 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

if 语句

教学大纲

学习目标 2.3.A: 使用选择语句开发代码来表示分支逻辑过程,并确定这些过程的结果。

  • 2.3.A.1 选择语句会改变语句的顺序执行。
  • 2.3.A.2 if 语句是一种选择语句,它通过根据布尔表达式的值执行不同的代码段来影响控制流。
  • 2.3.A.3 单向选择(if 语句)用于在特定条件下需要执行某段代码的情况。在这种情况下,仅当布尔表达式为 true 时才执行其主体部分。
  • 2.3.A.4 双向选择(if-else 语句)用于存在两段代码的情况:一段在布尔表达式为 true 时执行,另一段在布尔表达式为 false 时执行。在这种情况下,当布尔表达式为 true 时执行 if 的主体部分,当布尔表达式为 false 时执行 else 的主体部分。

来源:College Board AP 课程与考试说明

English

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");
}
Traffic lights: selection chooses which branch runs, just as if statements choose code paths
Traffic lights: selection chooses which branch runs, just as if statements choose code paths

Common mistakes.

  • A semicolon after the condition ends the if: in if (x > 0); { count++; } the block runs every time.
  • Without braces only one statement belongs to the if. Below, "Done" prints whatever t is, despite the indentation:
if (t > 30)
    System.out.println("Hot");
    System.out.println("Done");
探索

查看 if 选择哪个分支

当条件为真时,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

嵌套 if 语句

教学大纲

学习目标 2.4.A: 编写代码来表示嵌套分支逻辑过程,并确定这些过程的结果。

  • 2.4.A.1 嵌套 if 语句是指包含在 if、if-else 或 if-else-if 语句内部的 if、if-else 或 if-else-if 语句。
  • 2.4.A.2 内部嵌套 if 语句的布尔表达式仅在外部 if 语句的布尔表达式求值为 true 时才会被评估。
  • 2.4.A.3 当存在一系列表达式且每个条件对应不同的代码段时,使用 多路选择(if-else-if)。多路选择的执行方式是:仅基于第一个求值为 true 的表达式执行一个代码段。如果没有任何表达式求值为 true 且存在尾随的 else 语句,则执行 else 的代码块。

来源:College Board AP 课程与考试说明

English

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

复合布尔表达式

教学大纲

学习目标 2.5.A: 编写代码表示复合布尔表达式,并确定这些表达式的结果。

  • 2.5.A.1 逻辑运算符 !(非)、&&(与)和 ||(或)用于布尔表达式。如果 a 为 false,则表达式 !a 计算结果为 true;否则计算结果为 false。如果 a 和 b 均为 true,则表达式 a && b 计算结果为 true;否则计算结果为 false。如果 a 为 true、b 为 true 或两者皆是,则表达式 a || b 计算结果为 true;否则计算结果为 false。逻辑运算符的求值优先级顺序为 !(非),然后是 &&(与),最后是 ||(或)。涉及逻辑运算符的表达式将计算出一个布尔值。
  • 2.5.A.2 当使用 && 或 || 的逻辑运算的结果可以通过仅评估第一个布尔表达式来确定时,就会发生短路求值。在这种情况下,不会评估第二个布尔表达式。

来源:College Board AP 课程与考试说明

English
Short-circuit evaluation

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

Truth table for &&, || and !, with short-circuit evaluation
Truth table for &&, || and !, with short-circuit evaluation

Worked example. Evaluate !(x > y) || x < 5 && y == 6 for x = 4, y = 6. The order is !, then &&, then ||:

  1. x > y is 4 > 6, false, so !(x > y) is true.
  2. x < 5 && y == 6 is true && true, true.
  3. 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

比较布尔表达式

教学大纲

学习标准 2.6.A: 比较等价的布尔表达式。

  • 2.6.A.1 如果两个布尔表达式在所有情况下求值结果相同,则它们是等价的。可以使用真值表来证明布尔表达式是等价的。
  • 2.6.A.2 德摩根定律可以应用于布尔表达式以创建等价的布尔表达式。根据德摩根定律,布尔表达式 !(a && b) 等价于 !a || !b,布尔表达式 !(a || b) 等价于 !a && !b。

学习标准 2.6.B: 开发代码使用布尔表达式比较对象引用并确定这些表达式的结果。

  • 2.6.B.1 两个不同的变量可以持有指向同一对象的引用。可以使用 == 和 != 比较对象引用。
  • 2.6.B.2 可以使用 == 或 != 将对象引用与 null 进行比较,以确定该引用是否实际指向一个对象。
  • 2.6.B.3 类通常定义自己的 equals 方法,可用于指定该类两个对象的等价性标准。两个对象的等价性通常通过这两个对象的属性来确定。
    • 排除项: 重写(Override)equals 方法不在 AP 计算机科学 A 课程和考试范围内。

来源:College Board AP 课程与考试说明

English

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

  1. De Morgan: !(age >= 13) || !(age <= 19) (the && becomes ||).
  2. Negate each comparison: !(age >= 13) is age < 13; !(age <= 19) is age > 19.
  3. Result: 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

while 循环

教学大纲

学习目标 2.7.A: 识别何时需要迭代过程才能达到预期结果。

  • 2.7.A.1 迭代是一种重复形式。迭代语句通过重复一段代码零次或多次来改变控制流,只要控制循环的布尔表达式求值结果为 true,就会持续重复。
  • 2.7.A.2 当迭代语句中的布尔表达式始终求值为 true 时,会发生无限循环。
  • 2.7.A.3 如果布尔表达式初始求值结果为 false,则迭代语句的循环体将不会执行。
  • 2.7.A.4 当迭代语句多循环一次或少循环一次时,会发生差一错误(off by one errors)。

学习目标 2.7.B: 使用 while 循环开发表示迭代过程的代码,并确定这些过程的结果。

  • 2.7.B.1 while 循环是迭代语句的一种类型。在 while 循环中,每次循环体迭代之前都会评估布尔表达式,包括第一次迭代。当表达式求值为 true 时,执行循环体。这一过程会一直持续,直到布尔表达式求值为 false,此时迭代终止。

来源:College Board AP 课程与考试说明

English

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 无限循环:

The three loop types differ in where the condition is tested
The three loop types differ in where the condition is tested
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 循环

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

for 循环

教学大纲

学习目标 2.8.A: 编写代码,使用 for 循环表示迭代过程并确定这些过程的结果。

  • 2.8.A.1 for 循环是一种迭代语句。for 循环头部包含三个部分:初始化、布尔表达式和更新。
  • 2.8.A.2 在 for 循环中,初始化语句仅在第一次评估布尔表达式之前执行一次。被初始化的变量称为 循环控制变量。在循环控制变量初始化后立即评估布尔表达式,随后在每次执行增量语句后再次评估,直到其为 false。在每次迭代中,更新操作在整个循环体执行完毕后、再次评估布尔表达式之前执行。
  • 2.8.A.3 for 循环可以重写为等价的 while 循环(反之亦然)。

来源:College Board AP 课程与考试说明

English

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.

An assembly line: loops repeat a process for every item, like for and while
An assembly line: loops repeat a process for every item, like for and while
The three parts of a for loop and the order they run
The three parts of a for loop and the order they run
探索

追踪 for 循环

for 循环运行固定次数,其计数器逐步遍历一个范围。观察计数器与累计和每次迭代时的推进过程。

词汇 训练
English 中文 拼音
initialization 初始化 chū shǐ huà
update/ˈʌpdeɪt/ 更新 gēng xīn
2.9

实现选择与迭代算法

教学大纲

学习目标 2.9.A: 为标准和原创算法(不使用数据结构)编写代码,并确定这些算法的结果。

  • 2.9.A.1 存在以下标准算法:
    • 判断一个整数是否能被另一个整数整除
    • 提取一个整数的各个数位
    • 统计满足特定条件的次数
    • 确定最小值或最大值
    • 计算总和或平均值

来源:College Board AP 课程与考试说明

English

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

实现字符串算法

教学大纲

学习目标 2.10.A: 编写涉及字符串的标准及原创算法的代码,并确定这些算法的结果。

  • 2.10.A.1 存在标准字符串算法用于:
    • 查找一个或多个子串是否具有特定属性
    • 确定满足特定条件的子串数量
    • 创建一个字符顺序反转的新字符串

来源:College Board AP 课程与考试说明

English

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.

Reversing a string by walking its indexes backwards
Reversing a string by walking its indexes backwards
词汇 训练
English 中文 拼音
index/ˈɪndeks/ 索引 suǒ yǐn
character/ˈkærɪktə/ 字符 zì fú
occurrences 出现次数 chū xiàn cì shù
2.11

嵌套迭代

教学大纲

学习目标 2.11.A: 编写代码以表示嵌套迭代过程,并确定这些过程的结果。

  • 2.11.A.1 嵌套迭代语句是指出现在另一个迭代语句主体中的迭代语句。当循环嵌套在另一个循环内部时,内层循环必须完成其所有迭代后,外层循环才能继续进入下一次迭代。

来源:College Board AP 课程与考试说明

English

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.

The inner loop runs completely for each pass of the outer loop
The inner loop runs completely for each pass of the outer loop

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

非正式运行时间分析

教学大纲

学习目标 2.12.A: 计算语句执行次数并对迭代语句进行非正式的运行时比较。

  • 2.12.A.1 语句执行次数(statement execution count)指程序执行某条语句的次数。语句执行次数通常通过对迭代语句进行追踪和分析来进行非正式计算。

来源:College Board AP 课程与考试说明

English
Big-O growth rates

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 效率.

How the running time grows with the number of elements n
How the running time grows with the number of elements n

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ǜ
2.12

考试技巧

English
  • Get boundary conditions 边界条件 right: use < vs <= deliberately, and watch the first and last iteration of every loop (off-by-one 差一错误 is the classic bug 缺陷).
  • Build compound conditions with &&, ||, ! and remember short-circuit evaluation (put the null check first).
  • Trace nested loops by counting how many times the inner body runs in total.
  • Choose the right structure — if/else if for ranges, a loop for repetition — and avoid an infinite loop by updating the loop variable 循环变量.
  • Apply De Morgan's laws when you simplify or negate a boolean condition.
词汇 训练
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

该知识点的互动课程

逐步完成,配合即时检查练习。

历年真题

更多 AP 计算机科学 A 知识点

登录或创建账户

IGCSE, A-Level & AP