Skip to content

Selection and Iteration

AP Computer Science A · Topic 2

Video lesson for this topic Open the video page
7:58

Selection and Iteration

Here are three loops. The first two differ by one character — a less-than instead of a less-than-or-equal. The first runs ten times. The second runs eleven.…

English narration · English + 中文 subtitles burned in

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

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
Vocabulary Train
English
Algorithms/ˈælɡərɪθəmz/
control structures/kənˈtrəʊl ˈstrʌktʃəz/
sequence/ˈsiːkwəns/
selection/sɪˈlekʃn/
iteration/ˌɪtəˈreɪʃn/
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.

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
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
boolean expression/ˈbuːlɪən ekˈspreʃn/
relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/
primitive values
object references
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");
}
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");
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
if statement/ɪf ˈsteɪtmənt/
block/blɒk/
condition/kənˈdɪʃn/
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';

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.

Vocabulary Train
English
branch/bræntʃ/
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).

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.

Vocabulary Train
English
Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/
short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/
guard against
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.

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
Explore

One matching row is not enough

Compare the original, De Morgan rewrite and unflipped candidate for every pair of pure Boolean inputs. A mismatch is a counterexample.

Vocabulary Train
English
De Morgan's laws/də ˈmɔːɡənz lɔːz/
equivalent/ɪˈkwɪvələnt/
truth table/truːθ ˈteɪbl/
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++;
}

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.

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
while loop/waɪl luːp/
infinite loop/ˈɪnfɪnət luːp/
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.

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

Vocabulary Train
English
initialization
update/ˈʌpdeɪt/
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 /. 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.

Vocabulary Train
English
digits
integer/ˈɪntɪdʒə/
divisibility
counter/ˈkaʊntə/
frequency/ˈfriːkwənsi/
criterion/kraɪˈtɪərɪən/
running total
flag/flæɡ/
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.

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
Vocabulary Train
English
index/ˈɪndeks/
character/ˈkærɪktə/
occurrences
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 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.

Vocabulary Train
English
nested loop/ˈnestɪd luːp/
inner loop/ˈɪnə luːp/
outer loop/ˈaʊtə luːp/
grids
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: 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.

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
Run-time analysis/rʌn taɪm əˈnæləsɪs/
linear/ˈlɪnɪə/
quadratic/kwɒˈdrætɪk/
efficiency/ɪˈfɪʃənsi/
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.
Vocabulary Train
English
boundary conditions
off-by-one
bug/bʌɡ/
loop variable

Interactive lessons on this topic

Work through it step by step, with instant-check exercises.

Past Papers

More topics in AP Computer Science A

Log in or create account

IGCSE, A-Level & AP