Skip to content

Selection and Iteration

AP Computer Science A · Topic 2

Train
2.1

Selection and Repetition in Algorithms

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

Source: College Board AP Course and Exam Description

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

Vocabulary Train
English Chinese Pinyin
control structures 控制结构 kòng zhì jié gòu
selection 选择 xuǎn zé
iteration 迭代 dié dài
2.2

Boolean Expressions

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

Source: College Board AP Course and Exam Description

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.

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

Explore

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.

Vocabulary Train
English Chinese Pinyin
boolean expression 布尔表达式 bù ěr biǎo dá shì
relational operators 关系运算符 guān xì yùn suàn fú
2.3

The if Statement

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

Source: College Board AP Course and Exam Description

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");
}
Explore

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.

Vocabulary Train
English Chinese Pinyin
if statement 条件语句 tiáo jiàn yǔ jù
2.4

Nested if Statements

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

Source: College Board AP Course and Exam Description

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';
2.5

Compound Boolean Expressions

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

Source: College Board AP Course and Exam Description

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

Vocabulary Train
English Chinese Pinyin
Logical operators 逻辑运算符 luó jí yùn suàn fú
short-circuit evaluation 短路求值 duǎn lù qiú zhí
2.6

Comparing Boolean Expressions

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

Source: College Board AP Course and Exam Description

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.

Vocabulary Train
English Chinese Pinyin
De Morgan's laws 德摩根定律 dé mó gēn dìng lǜ
2.7

while Loops

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

Source: College Board AP Course and Exam Description

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++;
}
Explore

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.

Vocabulary Train
English Chinese Pinyin
while loop 循环 xún huán
infinite loop 无限循环 wú xiàn xún huán
2.8

for Loops

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

Source: College Board AP Course and Exam Description

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.

Explore

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

Building Complete Selection and Iteration Algorithms

Syllabus
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

Source: College Board AP Course and Exam Description

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 /. To read the digits of an integer one at a time, repeatedly take n % 10 (the last digit) and then n = n / 10 (drop it). To test divisibility, n % d == 0 means n is evenly divisible by d. Combine them with a counter to find the frequency with which some criterion is met.

Standard patterns like a running total, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.

Vocabulary Train
English Chinese Pinyin
flag 标志 biāo zhì
2.10

String Algorithms

Syllabus
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

Source: College Board AP Course and Exam Description

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.

2.11

Nested Iteration

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

Source: College Board AP Course and Exam Description

A nested loop 嵌套循环 puts one loop inside another; the inner loop completes fully for each pass of the outer. 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.

Vocabulary Train
English Chinese Pinyin
nested loop 嵌套循环 qiàn tào xún huán
2.12

Informal Run-Time Analysis

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

Source: College Board AP Course and Exam Description

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: a single loop over $n$ items is linear ($n$ steps); two nested loops over $n$ 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.

Explore

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

Vocabulary Train
English Chinese Pinyin
Run-time analysis 运行时间分析 yùn xíng shí jiān fēn xī
2.12

Exam tips

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

Log in or create account

IGCSE & A-Level