---
title: "AP CSA Unit 2 Review: Selection and Iteration | Fiveable"
description: "AP Computer Science A Unit 2 covers Algorithms with Selection and Repetition and Boolean Expressions. Study guides, practice questions, and key terms."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-2"
type: "unit"
subject: "AP Computer Science A"
unit: "Unit 2 – Selection and Iteration"
---

# AP CSA Unit 2 Review: Selection and Iteration | Fiveable

## Overview

Unit 2 introduces the decision-making and repetition tools that turn a linear sequence of statements into a real program. You will write Boolean expressions with relational and logical operators, use if and nested if statements to branch, write while and for loops to repeat code, apply standard algorithms like digit extraction and min/max tracking, process strings with loops, trace nested loops, and count statement executions to compare iterative code informally.

## AP CED Alignment

This unit hub is organized around AP Course and Exam Description topics, skills, and exam task types when they are available in the source data.
- 2.1: Algorithms with Selection and Repetition
- 2.2: Boolean Expressions
- 2.3: if Statements
- 2.4: Nested if Statements
- 2.5: Compound Boolean Expressions
- 2.6: Comparing Boolean Expressions
- 2.7: while Loops
- 2.8: for Loops
- 2.9: Implementing Selection and Iteration Algorithms
- 2.10: Implementing String Algorithms
- 2.11: Nested Iteration
- 2.12: Informal Run-Time Analysis
- 2.6: 2.6 Equivalent Boolean Expressions
- 2.1: Algorithms with selection and repetition
- 2.2: Boolean expressions and relational operators
- 2.3-2.4: if statements and nested if statements
- 2.5-2.6: Compound Boolean expressions and equivalence
- 2.7: while loops
- 2.8: for loops
- 2.9: Implementing selection and iteration algorithms
- 2.10: String algorithms
- 2.11: Nested iteration
- 2.12: Informal run-time analysis
- Practice 4 - Document Code and Computing Systems
- Practice 2 - Develop Code
- Practice 3 - Analyze Code
- FRQ 1 – Methods and Control Structures

## Topics

- [2.1: Algorithms with Selection and Repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe): Introduces the three building blocks of algorithms: sequencing, selection, and repetition. You represent algorithms in plain language or diagrams before coding them in Java.
- [2.2: Boolean Expressions](/ap-comp-sci-a/unit-2/boolean-expressions/study-guide/s6j4i9ram3AlCg3uYjwd): Covers relational operators ==, !=, <, >, <=, >= and the rule that primitive comparisons check values while reference comparisons check memory addresses.
- [2.3: if Statements](/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO): Introduces one-way (if) and two-way (if-else) selection. The body of an if runs only when its Boolean expression is true; the else body runs when it is false.
- [2.4: Nested if Statements](/ap-comp-sci-a/unit-2/if-else-statements/study-guide/t6FfmE9rwA4mdWqv2ogR): Covers nested if statements and multiway if-else-if chains. The inner condition is only evaluated when the outer condition is true; the first true branch in a chain runs and the rest are skipped.
- [2.5: Compound Boolean Expressions](/ap-comp-sci-a/unit-2/compound-boolean-expressions/study-guide/WVkDsh43kiP30BIqg3Sh): Introduces !, &&, and || with precedence order ! then && then ||. Short-circuit evaluation means the second operand may not be evaluated.
- [2.6: Comparing Boolean Expressions](/ap-comp-sci-a/unit-2/boolean-expressions/study-guide/s6j4i9ram3AlCg3uYjwd): Covers Boolean equivalence, truth tables, De Morgan's law, and comparing object references with == and != including null checks and .equals().
- [2.7: while Loops](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi): A while loop checks its condition before every iteration. It can run zero times, and it causes an infinite loop if the condition never becomes false. Off-by-one errors are common.
- [2.8: for Loops](/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt): A for loop header contains initialization, Boolean condition, and update. Initialization runs once; the condition is checked before each iteration; the update runs after each body execution.
- [2.9: Implementing Selection and Iteration Algorithms](/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU): Standard algorithms using loops and conditionals: divisibility with %, digit extraction with % and /, frequency counting, min/max tracking, and sum/average with accumulators.
- [2.10: Implementing String Algorithms](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW): String algorithms use charAt, substring, length, and indexOf inside loops to check substring properties, count matches, and build reversed strings.
- [2.11: Nested Iteration](/ap-comp-sci-a/unit-2/nested-iteration/study-guide/Buapg1KURHNbw6yRY8EZ): The inner loop completes all its iterations each time the outer loop advances once. Total execution count is the product of bounds for independent loops or triangular for dependent bounds.
- [2.12: Informal Run-Time Analysis](/ap-comp-sci-a/unit-2/informal-code-analysis/study-guide/CR84MbOE4FDDoSVokDVZ): Count how many times a statement executes by tracing loop bounds. Single loops are linear; independent nested loops are quadratic; triangular nested loops produce n(n-1)/2 executions.
- [2.6: 2.6 Equivalent Boolean Expressions](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL): Review AP Computer Science A Topic 2.6, including equivalent Boolean expressions, comparing Boolean expressions, truth tables, De Morgan's law, !(a && b), !(a || b), ==, !=, null checks, and .equals().

## Hardest Topics And Analytics

Snapshot: practice snapshot
This snapshot uses Fiveable practice activity to show where students tend to miss questions and which review moves are worth prioritizing first.
- **70% average MCQ accuracy** (Across 5.3k multiple-choice practice attempts for this unit.)
- **5.3k MCQ attempts** (Practice activity included in this snapshot.)

## Review Notes

### 2.1: Algorithms with selection and repetition

An algorithm is a step-by-step process for solving a problem. The three building blocks are sequencing (executing statements in order), selection (branching based on a true or false condition), and repetition (looping until a goal is reached). You can represent algorithms in plain language or with flowcharts before writing Java code. The order in which these building blocks appear changes the outcome.

- **Sequencing**: Statements execute in the order they are written; changing the order changes the result.
- **Selection**: A true or false decision determines which path the algorithm takes at a branch point.
- **Repetition**: A process repeats until a desired outcome is reached, modeled with loops in Java.
- **Flowchart decision diamond**: A diamond shape in a diagram represents a true or false question that splits the algorithm into two paths.

**Checkpoint:** Describe a real-world task, such as sorting mail, using all three building blocks. Identify where the selection and repetition occur.

Building block | Java construct | When to use
--- | --- | ---
Sequencing | Statements in order | Steps that must happen in a fixed sequence
Selection | if, if-else, if-else-if | Different actions needed for different conditions
Repetition | while, for | Same action needed multiple times until a goal is met

### 2.2: Boolean expressions and relational operators

A Boolean expression evaluates to either true or false. Relational operators compare two values and produce a Boolean result. With primitive types, == and != compare actual values. With reference types, == and != compare object references, not content. To compare String content, use .equals().

- **Relational operator**: ==, !=, <, >, <=, >= compare two values and return a Boolean result.
- **Primitive comparison**: int, double, and char values compared with == check the actual stored value.
- **Reference comparison**: Using == on two object variables checks whether they point to the same object in memory, not whether their contents are equal.
- **Equality comparison**: For objects, use .equals() to test content equality; use == only to test whether two variables reference the exact same object.

**Checkpoint:** Write a Boolean expression that is true when an int variable score is between 70 and 89 inclusive. Then explain why you cannot use == to compare two String variables for equal content.

Operand type | Operator | What is compared
--- | --- | ---
int, double, char | ==, !=, <, >, <=, >= | Actual primitive values
Object references | ==, != | Memory addresses (same object?)
String content | .equals() | Character-by-character content

### 2.3-2.4: if statements and nested if statements

An if statement changes sequential flow by running a block only when its Boolean expression is true. An if-else adds a second block for when the condition is false. Nested if statements place one decision inside another; the inner condition is only evaluated when the outer condition is true. A multiway if-else-if chain checks conditions in order and executes the first true branch, then skips all remaining branches. If no condition is true and a trailing else exists, that else block runs.

- **One-way selection**: An if statement runs its body only when the condition is true; nothing happens when it is false.
- **Two-way selection**: An if-else runs one block when the condition is true and the other when it is false; exactly one block always runs.
- **Nested if**: An if or if-else placed inside another if block; the inner condition is only reached when the outer condition is true.
- **Multiway selection**: An if-else-if chain evaluates conditions top to bottom and executes only the first true branch.
- **Trailing else**: An else at the end of an if-else-if chain that runs when no earlier condition was true.

**Checkpoint:** Trace this logic: a variable grade is 85. An if-else-if checks grade >= 90 first, then grade >= 80, then grade >= 70, with a trailing else. Which block runs and why?

Form | Blocks that can run | When to use
--- | --- | ---
if | 0 or 1 | Optional action under one condition
if-else | Exactly 1 of 2 | Two mutually exclusive outcomes
if-else-if | 0 or 1 of many | Multiple mutually exclusive categories
Nested if | Depends on outer | Layered conditions where inner depends on outer

### 2.5-2.6: Compound Boolean expressions and equivalence

Logical operators combine Boolean expressions. ! (not) negates a value. && (and) is true only when both operands are true. || (or) is true when at least one operand is true. Precedence order is !, then &&, then ||. Short-circuit evaluation means Java stops evaluating as soon as the result is determined: for &&, if the left side is false, the right side is skipped; for ||, if the left side is true, the right side is skipped. Two Boolean expressions are equivalent if they produce the same result for every possible input. De Morgan's law gives two key equivalences: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Truth tables prove equivalence by listing all input combinations.

- **Short-circuit evaluation**: Java stops evaluating && when the left operand is false, and stops evaluating || when the left operand is true, so the right operand may never be checked.
- **De Morgan's law**: !(a && b) is equivalent to !a || !b; !(a || b) is equivalent to !a && !b. Use these to rewrite negated compound conditions.
- **Truth tables**: A table listing all true/false combinations for variables to verify that two Boolean expressions always produce the same output.
- **Operator precedence**: ! is evaluated first, then &&, then ||. Use parentheses to override this order when needed.
- **Null comparison**: Use obj == null or obj != null to check whether a reference variable holds an object before calling methods on it.

**Checkpoint:** Apply De Morgan's law to rewrite !(x > 5 && y < 10) without the outer negation. Then build a truth table for a && !b to verify your understanding.

Operator | True when | Short-circuits when
--- | --- | ---
! | Operand is false | Always (single operand)
&& | Both operands are true | Left operand is false
|| | At least one operand is true | Left operand is true

### 2.7: while loops

A while loop evaluates its Boolean condition before every iteration, including the first. If the condition is false initially, the loop body never runs. The loop continues as long as the condition is true. If the condition never becomes false, the result is an infinite loop. Off-by-one errors occur when the loop runs one time too many or too few, usually because the condition uses < instead of <= or vice versa. A loop control variable must be initialized before the loop and updated inside the loop body.

- **Pretest loop**: A while loop checks its condition before the body runs, so it can execute zero times if the condition starts false.
- **Infinite loop**: Occurs when the loop condition always evaluates to true because the loop variable is never updated or the update does not move toward termination.
- **Off by one error**: The loop runs one iteration too many or too few, often caused by using < vs <= or initializing the counter incorrectly.
- **Accumulator pattern**: Initialize a variable before the loop, then update it inside the loop body each iteration to build a running total or count.

**Checkpoint:** Write a while loop that sums integers from 1 to 10. Identify the initialization, condition, body, and update. Then change the condition to cause an off-by-one error and explain what goes wrong.

### 2.8: for loops

A for loop header has three parts: initialization (runs once before the first condition check), Boolean expression (checked before every iteration), and update (runs after every loop body execution). The variable declared in the initialization is the loop control variable. A for loop can always be rewritten as an equivalent while loop and vice versa. For loops are preferred when the number of iterations is known in advance.

- **Loop control variable**: The variable declared in the for loop initialization, used to count iterations and control when the loop ends.
- **Initialization**: Runs exactly once before the first condition check; sets the starting value of the loop control variable.
- **Update**: Runs after every execution of the loop body and before the next condition check; typically increments or decrements the loop control variable.
- **for-to-while conversion**: Any for loop can be rewritten as a while loop by moving initialization before the loop and the update to the end of the loop body.

**Checkpoint:** Trace a for loop with header for(int i = 1; i <= 5; i++) that prints i * i. List the value of i and the output for each iteration. Then rewrite it as an equivalent while loop.

Loop type | Condition checked | Best use case
--- | --- | ---
while | Before each iteration (pretest) | Unknown number of iterations; event-driven termination
for | Before each iteration (pretest) | Known number of iterations; index-based traversal

### 2.9: Implementing selection and iteration algorithms

Standard algorithms combine if statements and loops to solve common problems without using arrays. The modulus operator % finds remainders and tests divisibility. Digit extraction uses % 10 to get the last digit and integer division by 10 to remove it, repeating in a loop. Frequency counting uses a conditional increment inside a loop. Min and max tracking initializes a variable to the first value and updates it when a new value is smaller or larger. Sum and average use an accumulator variable updated each iteration.

- **Digit extraction**: Use n % 10 to get the ones digit and n / 10 to shift right; repeat in a while loop until n equals 0.
- **Accumulator variable**: Initialized before the loop and updated inside it to compute a running sum, count, or other aggregate value.
- **Maximum value algorithm**: Initialize a max variable, then compare each new value to max inside a loop and update max when a larger value is found.
- **Count variable**: Incremented inside a loop only when a condition is true, used to count how many values meet a specific criterion.

**Checkpoint:** Write a loop that counts how many digits in a positive integer are greater than 5. Identify which standard algorithm patterns you are combining.

Algorithm | Key operation | Pattern
--- | --- | ---
Divisibility check | n % d == 0 | Single Boolean expression
Digit extraction | n % 10, n / 10 | while loop, shrink n each pass
Frequency count | if condition, count++ | Accumulator with conditional increment
Min/max tracking | if new > max, update | Accumulator with conditional update
Sum and average | sum += value | Accumulator, divide by count at end

### 2.10: String algorithms

String algorithms use loops with String methods to examine text one character or substring at a time. The three standard goals are checking whether substrings have a property, counting substrings that meet criteria, and building a reversed string. Key methods are charAt(i) to get a character at index i, substring(start, end) to extract a portion, length() to get the string length, and indexOf() to search. Loop bounds matter: valid indices run from 0 to length() - 1. Strings are immutable, so building a new string requires concatenation or a new variable.

- **charAt**: Returns the char at a given index; valid indices are 0 through length() - 1.
- **substring**: substring(start, end) returns characters from index start up to but not including index end.
- **String immutability**: Strings cannot be changed in place; operations like reversal require building a new String variable.
- **Overlapping occurrences**: When counting substring matches, decide whether overlapping instances count separately; adjust the loop index accordingly.

**Checkpoint:** Write a loop that builds the reverse of a String s by concatenating characters from the last index to index 0. Identify the loop bounds and explain why length() - 1 is the correct starting index.

### 2.11: Nested iteration

Nested iteration places one loop inside another. The inner loop completes all of its iterations every time the outer loop runs once. To trace nested loops, track both loop variables together. The total number of inner loop body executions is the product of the outer and inner iteration counts for independent bounds. When inner bounds depend on the outer variable, the count is triangular.

- **Inner loop reset**: Each time the outer loop advances one iteration, the inner loop variable resets to its initial value and runs through all its iterations again.
- **Dependent inner bounds**: When the inner loop runs from 0 to i (the outer variable), the total iterations form a triangular pattern: 0 + 1 + 2 + ... + (n-1) = n(n-1)/2.
- **Cartesian product**: Independent nested loops with bounds m and n produce m * n total inner loop executions, one for each (i, j) pair.

**Checkpoint:** Trace a nested loop where the outer runs i from 0 to 2 and the inner runs j from 0 to i. List every (i, j) pair that executes and count the total inner loop body executions.

Loop structure | Total inner executions | Example
--- | --- | ---
Independent bounds (m outer, n inner) | m * n | for i 0..2, for j 0..3: 12 executions
Dependent bounds (inner 0 to i) | n(n-1)/2 | for i 0..4, for j 0..i: 10 executions

### 2.12: Informal run-time analysis

A statement execution count is the number of times a specific statement runs. You find it by tracing the loop structure and counting iterations. For a single loop running n times, a statement in the body executes n times. For independent nested loops with bounds m and n, the inner body executes m * n times. For a triangular nested loop, the inner body executes approximately n squared divided by 2 times. Informal run-time analysis compares two iterative segments by comparing their execution counts as input size grows, without requiring formal Big O notation.

- **Statement execution count**: The exact number of times a statement runs, determined by tracing loop bounds and conditions.
- **Linear iteration**: A single loop with bound n executes its body n times; execution count grows proportionally with n.
- **Quadratic iteration**: Independent nested loops with bound n each produce n * n inner body executions; count grows with the square of n.
- **Triangular loop count**: A nested loop where the inner bound depends on the outer variable produces approximately n(n-1)/2 inner executions.

**Checkpoint:** Given a nested loop where the outer runs from 1 to 4 and the inner runs from 1 to 3, calculate the exact execution count of a statement in the inner body. Then describe how the count changes if both bounds double.

Loop structure | Execution count formula | Growth type
--- | --- | ---
Single loop, bound n | n | Linear
Independent nested loops, bound n each | n * n | Quadratic
Triangular nested loop, bound n | n(n-1)/2 | Quadratic (slower constant)

## Study Guides

- [2.1 Algorithms with Selection and Repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe)
- [2.7 While Loops](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi)
- [2.6 Equivalent Boolean Expressions](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL)
- [2.11 Nested Iteration](/ap-comp-sci-a/unit-2/nested-iteration/study-guide/Buapg1KURHNbw6yRY8EZ)
- [2.12 Informal Code Analysis](/ap-comp-sci-a/unit-2/informal-code-analysis/study-guide/CR84MbOE4FDDoSVokDVZ)
- [2.8 For Loops](/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt)
- [2.10 Developing Algorithms Using Strings](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW)
- [2.3 If Statements and Control Flow](/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO)
- [2.2 Boolean Expressions](/ap-comp-sci-a/unit-2/boolean-expressions/study-guide/s6j4i9ram3AlCg3uYjwd)
- [2.4 If-Else Statements](/ap-comp-sci-a/unit-2/if-else-statements/study-guide/t6FfmE9rwA4mdWqv2ogR)
- [2.9 Implementing Selection and Iteration Algorithms](/ap-comp-sci-a/unit-2/implementing-selection-and-iteration-algorithms/study-guide/ulqF0nPukr6rbwgDTCuU)
- [2.5 Compound Boolean Expressions](/ap-comp-sci-a/unit-2/compound-boolean-expressions/study-guide/WVkDsh43kiP30BIqg3Sh)

## Practice Preview

### Multiple-choice practice

- **AP-style practice question**: Practice 4 - Document Code and Computing Systems | Consider the following code segment:

```java
int runs = 0;
int n = /* missing initialization */;
for (int i = 1; i < n; i *= 2) {
    for (int j = 0; j < i; j++) {
        runs++;
    }
}
```

Which of the following replacements for `/* missing initialization */` will cause the `runs++;` statement to execute exactly 15 times?
- **AP-style practice question**: Practice 4 - Document Code and Computing Systems | Consider the following code segment.

```java
String str1 = /* missing initialization */;
String str2 = /* missing initialization */;
boolean diff = (str1 != str2) == str1.equals(str2);
```

Which of the following initial conditions will cause `diff` to evaluate to `true`?
- **AP-style practice question**: Practice 2 - Develop Code | The following method is intended to find the length of the longest word in a sentence. Words are separated by single spaces.

```java
public static int longestWordLen(String sentence) {
    int maxLen = 0;
    int currentLen = 0;
    for (int i = 0; i < sentence.length(); i++) {
        if (sentence.substring(i, i + 1).equals(" ")) {
            /* missing code */
        } else {
            currentLen++;
        }
    }
    if (currentLen > maxLen) {
        maxLen = currentLen;
    }
    return maxLen;
}
```

Which of the following can replace `/* missing code */` so the method works as intended?
- **AP-style practice question**: Practice 2 - Develop Code | The following method is intended to return a new string where any consecutive duplicate characters in `str` are reduced to a single character. For example, passing `"aabbbc"` should return `"abc"`.

```java
public static String cleanString(String str) {
    if (str.length() == 0) {
        return "";
    }
    String res = "" + str.charAt(0);
    for (int i = 1; i < str.length(); i++) {
        if (/* missing code */) {
            res += str.charAt(i);
        }
    }
    return res;
}
```

Which of the following can replace `/* missing code */` so the method works as intended?
- **AP-style practice question**: Practice 2 - Develop Code | A programmer is writing a method that takes a `String` and returns a new `String` containing every other character, starting with the first character (index 0). For example, `getEveryOther("computer")` should return `"cmue"`.

```java
public static String getEveryOther(String text) {
    String result = "";
    /* missing code */
    return result;
}
```

Which of the following can replace `/* missing code */` so the method works as intended?
- **AP-style practice question**: Practice 3 - Analyze Code | Consider the following method.

```java
public static String transform(int num) {
    String result = "";
    while (num > 0) {
        int digit = num % 10;
        if (digit % 2 != 0) {
            result = (digit + 1) + result;
        }
        num /= 10;
    }
    return result;
}
```

What is returned as a result of the call `transform(4725)`?

### FRQ practice

- **Token stream processing and community guideline flagging**: FRQ 1 – Methods and Control Structures | Token stream processing and community guideline flagging

## Key Terms

- **relational operator**: An operator that compares two values and returns a Boolean result. In AP CSA the relational operators are ==, !=, <, >, <=, and >=.
- **== (equality operator)**: Compares two values for equality. With primitives it compares actual values; with reference types it compares object references, not content.
- **short-circuit evaluation**: Java stops evaluating && when the left operand is false, and stops evaluating || when the left operand is true, so the right operand may never be checked.
- **De Morgan's law**: !(a && b) is equivalent to !a || !b, and !(a || b) is equivalent to !a && !b. Use these rules to rewrite negated compound conditions.
- **truth tables**: A table listing all true/false input combinations and their output for a Boolean expression, used to prove two expressions are equivalent.
- **off by one error**: A loop runs one iteration too many or too few because the condition uses < instead of <= or the counter is initialized incorrectly.
- **accumulator pattern**: A variable is initialized before a loop and updated inside the loop body each iteration to compute a running sum, count, or other aggregate.
- **accumulator variable**: The variable used in the accumulator pattern; initialized once and incremented or updated repeatedly during iteration.
- **digit extraction**: A standard algorithm that uses n % 10 to get the ones digit and n / 10 to remove it, repeated in a while loop until n equals 0.
- **maximum value algorithm**: Initialize a max variable to the first value, then compare each subsequent value inside a loop and update max when a larger value is found.
- **object reference**: A variable that holds a memory address pointing to an object. Using == on two reference variables checks whether they point to the same object.
- **null comparison**: Use obj == null or obj != null to check whether a reference variable holds an object before calling methods on it.
- **count variable**: A variable incremented inside a loop only when a condition is true, used to count how many values meet a specific criterion.

## Common Mistakes

- **Using == to compare String content**: == on two String variables checks whether they reference the same object, not whether they contain the same characters. Use .equals() to compare String content. This mistake causes code to behave correctly sometimes (when the JVM reuses the same literal) and fail other times.
- **Off-by-one errors in loop bounds**: Using < n when you need <= n, or starting at 1 instead of 0, causes the loop to run one iteration too few or too many. For String traversal, valid indices are 0 through length() - 1, so a loop condition of i < s.length() is correct; i <= s.length() causes an IndexOutOfBoundsException.
- **Forgetting to update the loop variable in a while loop**: If the variable that controls the while condition is never changed inside the loop body, the condition stays true forever and the loop never terminates. Always check that the loop body moves the control variable toward the termination condition.
- **Misapplying De Morgan's law**: A common error is distributing the negation without flipping the operator: !(a && b) is NOT !a && !b. The correct form is !a || !b. Write out a small truth table to verify any De Morgan's transformation before trusting it.
- **Assuming the inner loop retains its value across outer iterations**: In a nested for loop, the inner loop control variable is re-initialized every time the outer loop advances. Students sometimes trace as if the inner variable continues from where it left off, which produces incorrect output and execution counts.

## Exam Connections

- **Tracing code to predict output**: Multiple-choice questions frequently give a code segment with if statements, while loops, for loops, or nested loops and ask what value a variable holds or what the code prints. Practice tracing every statement in order, tracking variable values at each step, and applying short-circuit evaluation rules to compound conditions.
- **Writing and completing code segments**: Free-response questions ask you to write methods that use selection and iteration to implement a described algorithm. Common tasks include counting values that meet a condition, finding a minimum or maximum, processing characters in a String, and combining loops with if statements. Identify the algorithm pattern first, then write the loop structure and condition.
- **Identifying equivalent or correct Boolean logic**: Multiple-choice questions present two Boolean expressions and ask whether they are equivalent, or give a condition and ask which rewritten form produces the same result. Apply De Morgan's law, check operator precedence, and use a small truth table with two or three test cases to verify equivalence quickly.

## Final Review Checklist

- **Unit 2 final review checklist: Boolean expressions**: Write Boolean expressions using ==, !=, <, >, <=, >= and explain why == compares references for objects while .equals() compares content.
- **Unit 2 final review checklist: Selection statements**: Trace one-way if, two-way if-else, multiway if-else-if, and nested if statements to identify exactly which branch runs for a given input.
- **Unit 2 final review checklist: Compound Boolean expressions**: Apply !, &&, and || with correct precedence, use short-circuit evaluation to predict which operands are evaluated, and apply De Morgan's law to rewrite negated conditions.
- **Unit 2 final review checklist: while and for loops**: Trace while and for loops step by step, identify initialization, condition, body, and update, and convert between the two loop forms.
- **Unit 2 final review checklist: Standard algorithms**: Implement and trace divisibility checks, digit extraction, frequency counting, min/max tracking, and sum/average using loops and accumulators.
- **Unit 2 final review checklist: String algorithms**: Write loops using charAt, substring, and length to check substring properties, count matches, and reverse a String.
- **Unit 2 final review checklist: Nested loops and run-time analysis**: Trace nested loops to predict output and count inner body executions; distinguish linear, quadratic, and triangular execution counts.

## Study Plan

- **Step 1: Algorithms, Boolean expressions, and if statements (2.1-2.3)**: Read the topic guides for 2.1, 2.2, and 2.3. Practice writing Boolean expressions with all six relational operators and tracing one-way and two-way if statements with specific input values. Confirm you can explain why == fails for String content comparison.
- **Step 2: Nested if statements and compound Boolean expressions (2.4-2.6)**: Work through the topic guides for 2.4, 2.5, and 2.6. Trace multiway if-else-if chains with at least three branches. Practice applying De Morgan's law and build truth tables for && and || to verify equivalences. Use the key terms for short-circuit evaluation and De Morgan's law.
- **Step 3: while and for loops (2.7-2.8)**: Read the topic guides for 2.7 and 2.8. Write and trace at least three while loops and three for loops with different bounds. Convert each for loop to an equivalent while loop. Deliberately introduce an off-by-one error in one loop and explain what goes wrong.
- **Step 4: Standard algorithms and String algorithms (2.9-2.10)**: Work through the topic guides for 2.9 and 2.10. Implement each standard algorithm from scratch: divisibility, digit extraction, frequency count, min/max, sum/average, and String reversal. Trace each one with a specific input to verify correctness.
- **Step 5: Nested iteration and run-time analysis (2.11-2.12)**: Read the topic guides for 2.11 and 2.12. Trace nested loops with both independent and dependent bounds, listing every (i, j) pair. Calculate exact statement execution counts for single loops, independent nested loops, and triangular loops. Use the AP score calculator to estimate your estimated score range and identify which topic areas need more practice.

## More Ways To Review

- [Topic study guides](/ap-comp-sci-a/unit-2#topics)
- [FRQ practice](/ap-comp-sci-a/frq-practice)
- [Cheatsheets](/ap-comp-sci-a/cheatsheets/unit-2)
- [Key terms](/ap-comp-sci-a/key-terms)

## FAQs

### What topics are covered in AP CSA Unit 2?

AP CSA Unit 2 covers 12 topics focused on selection and iteration: Algorithms with Selection and Repetition, Boolean Expressions, `if` Statements, Nested `if` Statements, Compound Boolean Expressions, Comparing Boolean Expressions, `while` Loops, `for` Loops, Implementing Selection and Iteration Algorithms, Implementing String Algorithms, Nested Iteration, and Informal Run-Time Analysis. These topics build on each other, so Boolean expressions come before `if` statements, and single loops come before nested iteration. See [AP CSA Unit 2](/ap-comp-sci-a/unit-2) for practice on all 12 topics.

### How much of the AP CSA exam is Unit 2?

AP CSA Unit 2 makes up 25-35% of the AP exam, making it one of the heaviest-weighted units on the test. It covers selection (Boolean expressions, `if` statements, compound conditions) and iteration (`while` loops, `for` loops, nested iteration), which means these concepts show up constantly across both the multiple-choice and free-response sections.

### What's on the AP CSA Unit 2 progress check (MCQ and FRQ)?

The AP CSA Unit 2 progress check in AP Classroom includes both MCQ and FRQ parts drawn from the unit's 12 topics. The MCQ portion tests Boolean expressions, `if` and nested `if` statements, compound conditions, `while` loops, `for` loops, and informal run-time analysis. The FRQ portion asks you to write or trace code using selection and iteration, including string algorithms and nested loops. Working through the progress check is one of the best ways to find gaps before the real exam. You can find matched practice at [AP CSA Unit 2](/ap-comp-sci-a/unit-2).

### How do I practice AP CSA Unit 2 FRQs?

AP CSA Unit 2 FRQs typically ask you to write methods that use `if` statements, `while` loops, `for` loops, or nested iteration to solve a problem, and string algorithm questions are common too. To practice, write out full method bodies by hand, trace through your logic step by step, and check edge cases like empty strings or loop boundaries. Focus especially on topics 2.9 (Implementing Selection and Iteration Algorithms) and 2.10 (Implementing String Algorithms), since those map most directly to free-response writing. Find practice problems at [AP CSA Unit 2](/ap-comp-sci-a/unit-2).

### Where can I find AP CSA Unit 2 practice questions?

For AP CSA Unit 2 practice questions, including multiple-choice and practice test problems, head to [AP CSA Unit 2](/ap-comp-sci-a/unit-2). You'll find MCQ-style questions covering Boolean expressions, `if` statements, `while` and `for` loops, nested iteration, and run-time analysis, plus FRQ practice for string algorithms and implementing selection and iteration. Mixing MCQ drills with written FRQ attempts is the most effective way to prep for this unit's 25-35% exam weight.

### How should I study AP CSA Unit 2?

Start with Boolean expressions (topic 2.2) and `if` statements (2.3-2.5) before moving to loops, since selection logic is the foundation for everything else in this unit. Once conditions click, work through `while` loops (2.7) and `for` loops (2.8) separately, then practice nested iteration (2.11) and string algorithms (2.10) together since they combine both skills. Here's a concrete plan:
- Trace existing code by hand before writing your own, especially for nested loops.
- Write small methods from scratch for topics 2.9 and 2.10, then test edge cases.
- Use informal run-time analysis (2.12) to check whether your loops are efficient.
- Do a timed set of MCQs to catch tricky compound Boolean expression questions. Since this unit is 25-35% of the exam, it's worth revisiting it more than once. [AP CSA Unit 2](/ap-comp-sci-a/unit-2) has resources organized by topic to help you target weak spots.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#what-topics-are-covered-in-ap-csa-unit-2","name":"What topics are covered in AP CSA Unit 2?","acceptedAnswer":{"@type":"Answer","text":"AP CSA Unit 2 covers 12 topics focused on selection and iteration: Algorithms with Selection and Repetition, Boolean Expressions, `if` Statements, Nested `if` Statements, Compound Boolean Expressions, Comparing Boolean Expressions, `while` Loops, `for` Loops, Implementing Selection and Iteration Algorithms, Implementing String Algorithms, Nested Iteration, and Informal Run-Time Analysis. These topics build on each other, so Boolean expressions come before `if` statements, and single loops come before nested iteration. See <a href=\"/ap-comp-sci-a/unit-2\">AP CSA Unit 2</a> for practice on all 12 topics."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#how-much-of-the-ap-csa-exam-is-unit-2","name":"How much of the AP CSA exam is Unit 2?","acceptedAnswer":{"@type":"Answer","text":"AP CSA Unit 2 makes up 25-35% of the AP exam, making it one of the heaviest-weighted units on the test. It covers selection (Boolean expressions, `if` statements, compound conditions) and iteration (`while` loops, `for` loops, nested iteration), which means these concepts show up constantly across both the multiple-choice and free-response sections."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#whats-on-the-ap-csa-unit-2-progress-check-mcq-and-frq","name":"What's on the AP CSA Unit 2 progress check (MCQ and FRQ)?","acceptedAnswer":{"@type":"Answer","text":"The AP CSA Unit 2 progress check in AP Classroom includes both MCQ and FRQ parts drawn from the unit's 12 topics. The MCQ portion tests Boolean expressions, `if` and nested `if` statements, compound conditions, `while` loops, `for` loops, and informal run-time analysis. The FRQ portion asks you to write or trace code using selection and iteration, including string algorithms and nested loops. Working through the progress check is one of the best ways to find gaps before the real exam. You can find matched practice at <a href=\"/ap-comp-sci-a/unit-2\">AP CSA Unit 2</a>."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#how-do-i-practice-ap-csa-unit-2-frqs","name":"How do I practice AP CSA Unit 2 FRQs?","acceptedAnswer":{"@type":"Answer","text":"AP CSA Unit 2 FRQs typically ask you to write methods that use `if` statements, `while` loops, `for` loops, or nested iteration to solve a problem, and string algorithm questions are common too. To practice, write out full method bodies by hand, trace through your logic step by step, and check edge cases like empty strings or loop boundaries. Focus especially on topics 2.9 (Implementing Selection and Iteration Algorithms) and 2.10 (Implementing String Algorithms), since those map most directly to free-response writing. Find practice problems at <a href=\"/ap-comp-sci-a/unit-2\">AP CSA Unit 2</a>."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#where-can-i-find-ap-csa-unit-2-practice-questions","name":"Where can I find AP CSA Unit 2 practice questions?","acceptedAnswer":{"@type":"Answer","text":"For AP CSA Unit 2 practice questions, including multiple-choice and practice test problems, head to <a href=\"/ap-comp-sci-a/unit-2\">AP CSA Unit 2</a>. You'll find MCQ-style questions covering Boolean expressions, `if` statements, `while` and `for` loops, nested iteration, and run-time analysis, plus FRQ practice for string algorithms and implementing selection and iteration. Mixing MCQ drills with written FRQ attempts is the most effective way to prep for this unit's 25-35% exam weight."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2#how-should-i-study-ap-csa-unit-2","name":"How should I study AP CSA Unit 2?","acceptedAnswer":{"@type":"Answer","text":"Start with Boolean expressions (topic 2.2) and `if` statements (2.3-2.5) before moving to loops, since selection logic is the foundation for everything else in this unit. Once conditions click, work through `while` loops (2.7) and `for` loops (2.8) separately, then practice nested iteration (2.11) and string algorithms (2.10) together since they combine both skills. Here's a concrete plan:\n- Trace existing code by hand before writing your own, especially for nested loops.\n- Write small methods from scratch for topics 2.9 and 2.10, then test edge cases.\n- Use informal run-time analysis (2.12) to check whether your loops are efficient.\n- Do a timed set of MCQs to catch tricky compound Boolean expression questions. Since this unit is 25-35% of the exam, it's worth revisiting it more than once. <a href=\"/ap-comp-sci-a/unit-2\">AP CSA Unit 2</a> has resources organized by topic to help you target weak spots."}}]}
```
