跳到主要内容

选择与迭代

AP 计算机科学 A · 第 2 主题

训练
讲义 词汇表
2.1

带选择与重复的算法

大纲
Learning ObjectiveEssential Knowledge

2.1.A
Represent patterns and algorithms that involve selection and repetition found in everyday life using written language or diagrams.

  • 2.1.A.1 The building blocks of algorithms include sequencing, selection, and repetition.
  • 2.1.A.2 Algorithms can contain selection, through decision making, and repetition, via looping.
  • 2.1.A.3 Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
  • 2.1.A.4 Repetition is when a process repeats itself until a desired outcome is reached.
  • 2.1.A.5 The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm.

来源:美国大学理事会 AP 课程与考试说明

算法由三种控制结构(control structures)构建:顺序(sequence)(按顺序的步骤)、选择(selection)(选择一条路径),和迭代(iteration)(重复步骤)。这个主题涵盖选择和迭代——让一个程序做决定和循环的工具。

三种控制结构:顺序、选择和迭代
三种控制结构:顺序、选择和迭代
词汇表 训练
英文 中文 拼音
control structures 控制结构 kòng zhì jié gòu
selection 选择 xuǎn zé
iteration 迭代 dié dài
2.2

布尔表达式

大纲
Learning ObjectiveEssential Knowledge

2.2.A
Develop code to create Boolean expressions with relational operators and determine the result of these expressions.

  • 2.2.A.1 Values can be compared using the relational operators == and != to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references.
  • 2.2.A.2 Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values.
  • 2.2.A.3 An expression involving relational operators evaluates to a Boolean value.

来源:美国大学理事会 AP 课程与考试说明

逻辑门与半加器

一个布尔表达式(boolean expression)求值为 truefalse,用关系运算符(relational operators):==(相等)、!=(不相等)、<><=>=。注意 == 比较基本值但对对象比较对象引用,所以对 String.equals

三个运算符家族:算术、关系和逻辑
三个运算符家族:算术、关系和逻辑
探索

Explore the AND truth table

A Boolean expression evaluates to true or false. AND is true only when both operands are true; toggle the inputs to see all four cases.

词汇表 训练
英文 中文 拼音
boolean expression 布尔表达式 bù ěr biǎo dá shì
relational operators 关系运算符 guān xì yùn suàn fú
2.3

if 语句

大纲
Learning ObjectiveEssential Knowledge

2.3.A
Develop code to represent branching logical processes by using selection statements and determine the result of these processes.

  • 2.3.A.1 Selection statements change the sequential execution of statements.
  • 2.3.A.2 An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
  • 2.3.A.3 A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
  • 2.3.A.4 A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.

来源:美国大学理事会 AP 课程与考试说明

一个条件语句(if statement)只在它的条件为真时运行一个块;一个可选的 else 给出一个替代:

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
探索

See which branch an if chooses

An if statement runs its body only when the condition is true, otherwise it skips to else. Slide the score across the boundaries and watch the grade change.

词汇表 训练
英文 中文 拼音
if statement 条件语句 tiáo jiàn yǔ jù
2.4

嵌套 if 语句

大纲
Learning ObjectiveEssential Knowledge

2.4.A
Develop code to represent nested branching logical processes and determine the result of these processes.

  • 2.4.A.1 Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
  • 2.4.A.2 The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
  • 2.4.A.3 A multiway selection (if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multiway selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.

来源:美国大学理事会 AP 课程与考试说明

把一个 if 放进另一个里面,或用 else if 链接,按顺序测试几个情况。只有第一个匹配的分支运行:

if (g >= 90) grade = 'A';
else if (g >= 80) grade = 'B';
else grade = 'C';
2.5

复合布尔表达式

大纲
Learning ObjectiveEssential Knowledge

2.5.A
Develop code to represent compound Boolean expressions and determine the result of these expressions.

  • 2.5.A.1 Logical operators ! (not), && (and), and || (or) are used with Boolean expressions. The expression !a evaluates to true if a is false and evaluates to false otherwise. The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise. The expression a || b evaluates to true if a is true, b is true, or both, and evaluates to false otherwise. The order of precedence for evaluating logical operators is ! (not), && (and), then || (or). An expression involving logical operators evaluates to a Boolean value.
  • 2.5.A.2 Short-circuit evaluation occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated.

来源:美国大学理事会 AP 课程与考试说明

短路求值

逻辑运算符(logical operators)组合条件:&&(——两者都真)、||(——至少一个真)、!(——反转)。Java 用短路求值(short-circuit evaluation):&& 若左侧为假则停止,而 || 若左侧为真则停止——对防止错误有用,例如 if (n != 0 && total / n > 5)

词汇表 训练
英文 中文 拼音
Logical operators 逻辑运算符 luó jí yùn suàn fú
short-circuit evaluation 短路求值 duǎn lù qiú zhí
2.6

比较布尔表达式

大纲
Learning ObjectiveEssential Knowledge

2.6.A
Compare equivalent Boolean expressions.

  • 2.6.A.1 Two Boolean expressions are equivalent if they evaluate to the same value in all cases. Truth tables can be used to prove Boolean expressions are equivalent.
  • 2.6.A.2 De Morgan's law can be applied to Boolean expressions to create equivalent Boolean expressions. Under De Morgan's law, the Boolean expression !(a && b) is equivalent to !a || !b and the Boolean expression !(a || b) is equivalent to !a && !b.

2.6.B
Develop code to compare object references using Boolean expressions and determine the result of these expressions.

  • 2.6.B.1 Two different variables can hold references to the same object. Object references can be compared using == and !=.
  • 2.6.B.2 An object reference can be compared with null, using == or !=, to determine if the reference actually references an object.
  • 2.6.B.3 Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class. The equivalency of two objects is most often determined using attributes from the two objects.
    • Exclusion statement: Overriding the equals method is outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

德摩根定律(De Morgan's laws)重写否定:!(a && b) 等于 !a || !b,而 !(a || b) 等于 !a && !b。两个布尔表达式等价,若它们对每个输入给出相同的结果——一张真值表证明它。以这种方式化简条件是一个常见的考试任务。

词汇表 训练
英文 中文 拼音
De Morgan's laws 德摩根定律 dé mó gēn dìng lǜ
2.7

while 循环

大纲
Learning ObjectiveEssential Knowledge

2.7.A
Identify when an iterative process is required to achieve a desired result.

  • 2.7.A.1 Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true.
  • 2.7.A.2 An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
  • 2.7.A.3 The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
  • 2.7.A.4 Off by one errors occur when the iteration statement loops one time too many or one time too few.

2.7.B
Develop code to represent iterative processes using while loops and determine the result of these processes.

  • 2.7.B.1 A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.

来源:美国大学理事会 AP 课程与考试说明

一个循环(while loop)在它的条件保持为真时当……时重复,在每一趟之前测试。你必须在里面改变某样东西以便循环最终停止,否则它变成一个无限循环(infinite loop):

三种循环类型在条件被测试的地方不同
三种循环类型在条件被测试的地方不同
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}
探索

Trace a while loop

A while loop repeats as long as its condition stays true, updating its variables each pass. Step through to see the sum of squares build up.

词汇表 训练
英文 中文 拼音
while loop 循环 xún huán
infinite loop 无限循环 wú xiàn xún huán
2.8

for 循环

大纲
Learning ObjectiveEssential Knowledge

2.8.A
Develop code to represent iterative processes using for loops and determine the result of these processes.

  • 2.8.A.1 A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
  • 2.8.A.2 In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the increment statement until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
  • 2.8.A.3 A for loop can be rewritten into an equivalent while loop (and vice versa).

来源:美国大学理事会 AP 课程与考试说明

一个 for 循环(for loop)把初始化、条件和更新打包进一行——当你知道次数时最好:

for (int i = 0; i < n; i++) {
    // runs n times, i = 0..n-1
}

一个 for 和一个等价的 while 做相同的工作;能够在它们之间转换。

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
探索

Trace a for loop

A for loop runs a fixed number of times, its counter stepping through a range. Watch the counter and running total advance one pass at a time.

2.9

实现选择与迭代算法

大纲
Learning ObjectiveEssential Knowledge

2.9.A
Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.

  • 2.9.A.1 There are standard algorithms to:
    • identify if an integer is or is not evenly divisible by another integer
    • identify the individual digits in an integer
    • determine the frequency with which a specific criterion is met
    • determine a minimum or maximum value
    • compute a sum or average

来源:美国大学理事会 AP 课程与考试说明

组合循环和条件来解决真实的问题——计数、求和、找一个最大值,或测试一个性质:

int max = arr[0];
for (int k = 1; k < arr.length; k++) {
    if (arr[k] > max) max = arr[k];
}

有两个整数模式,考试会直接考,它们用 %/。要一次一个地读出一个整数的各位数字,反复取 n % 10(最后一位)然后 n = n / 10(把它去掉)。要测试整除性,n % d == 0 表示 n 能被 d 整除。把它们和一个计数器结合起来,就能求出某个标准被满足的频率

像一个连续总计、一个计数器,或一个标志(flag)(一个记录某事是否发生的布尔值)这样的标准模式贯穿整个课程重现。

词汇表 训练
英文 中文 拼音
flag 标志 biāo zhì
2.10

实现字符串算法

大纲
Learning ObjectiveEssential Knowledge

2.10.A
Develop code for standard and original algorithms that involve strings and determine the result of these algorithms.

  • 2.10.A.1 There are standard string algorithms to:
    • find if one or more substrings have a particular property
    • determine the number of substrings that meet specific criteria
    • create a new string with the characters reversed

来源:美国大学理事会 AP 课程与考试说明

按索引循环遍历一个字符串以处理每个字符:

for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    // count vowels, reverse, check for a substring, ...
}

典型的任务:计数出现、构建一个反转或过滤的副本,或测试一个字符串是否包含另一个。

2.11

嵌套迭代

大纲
Learning ObjectiveEssential Knowledge

2.11.A
Develop code to represent nested iterative processes and determine the result of these processes.

  • 2.11.A.1 Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.

来源:美国大学理事会 AP 课程与考试说明

一个嵌套循环(nested loop)把一个循环放进另一个里面;内层循环对外层的一趟完全完成。若外层运行 $n$ 次而内层 $m$ 次,主体运行 $n\times m$ 次——处理网格和比较所有对的基础。

词汇表 训练
英文 中文 拼音
nested loop 嵌套循环 qiàn tào xún huán
2.12

非正式运行时间分析

大纲
Learning ObjectiveEssential Knowledge

2.12.A
Calculate statement execution counts and informal run-time comparison of iterative statements.

  • 2.12.A.1 A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements.

来源:美国大学理事会 AP 课程与考试说明

大 O 增长率

运行时间分析(run-time analysis)数一个算法随着输入大小 $n$ 增长取多少基本步骤。数最内层语句的执行:一个遍历 $n$ 个项的单一循环是线性的($n$ 步);两个遍历 $n$ 的嵌套循环是二次的($n^2$)。这种非正式的计数让你能比较两个算法的效率。

运行时间如何随元素数量 n 增长
运行时间如何随元素数量 n 增长

考试技能: 对于一个嵌套循环,能够以循环边界陈述内层语句运行多少次——一个频繁的选择题。

Worked example. 这个打印多少个星?

for (int i = 0; i < 4; i++)
    for (int j = 0; j < i; j++)
        System.out.print("*");

内层循环对每个外层 i 运行 i 次:0 + 1 + 2 + 3 = 6 个星。当内层边界是外层变量时,总数是三角和 $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ ——这里 $\dfrac{4\times3}{2}=6$ ——不是一个矩形嵌套循环的完整 $n^2=16$

探索

Compare how algorithms scale

Run-time describes how the number of steps grows with the input size $n$. Increase $n$ and watch a linear $O(n)$ pull far ahead of a quadratic $O(n^2)$.

词汇表 训练
英文 中文 拼音
Run-time analysis 运行时间分析 yùn xíng shí jiān fēn xī
2.12

考试技巧

  • 把边界条件搞对:有意地用 < vs <=,并注意每个循环的第一次和最后一次迭代(差一是经典的 bug)。
  • &&||! 构建复合条件并记住短路求值(把 null 检查放在先)。
  • 通过数内层主体总共运行多少次来跟踪嵌套循环。
  • 选择正确的结构——if/else if 用于范围、一个循环用于重复——并通过更新循环变量避免一个无限循环。
  • 当你化简或否定一个布尔条件时应用德摩根定律

本主题的互动课程

逐步学习,并即时检测练习。

AP 计算机科学 A历年真题

AP 计算机科学 A的更多主题

登录或创建账号

IGCSE, A-Level & AP