Unit 2 Big Idea: Programs Do Not Just Run Top to Bottom
In Unit 1, code mostly executed one statement at a time from top to bottom. In Unit 2, students learn to control the path of execution. A program can choose between alternatives, repeat work, stop early, skip an iteration, or return a result from a method.
ifelse ifswitchforwhiledo-whilebreakcontinuereturnalgorithmic thinking
Control Structure Summary
| Control Category | Keywords Included | Key Practical Use Case | AP CSA Skill |
|---|---|---|---|
| Selection | if, else, else if, switch | Choosing between paths based on true/false conditions or exact values. | Trace condition order and identify which block executes. |
| Iteration | for, enhanced for, while, do-while | Automating repeated actions, counting, accumulating, searching, and simulating change. | Track loop variables, bounds, and updates. |
| Branching | break, continue, return | Stopping loops early, skipping one cycle, or immediately finishing a method. | Determine when execution exits a loop or method. |
1. Selection Statements: Decision-Making
Selection structures evaluate boolean conditions and route the program down different execution paths. The most important AP skill is recognizing that only certain blocks execute.
if
Executes a block only when the condition is true.
int temp = 88;
if (temp > 85) {
System.out.println("Too hot for hard intervals");
}if-else
Provides one path for true and one path for false.
int score = 72;
if (score >= 70) {
System.out.println("Pass");
} else {
System.out.println("Revise and retry");
}else-if ladder
Tests multiple conditions in order until one is true.
int grade = 87;
if (grade >= 90) {
System.out.println("A");
} else if (grade >= 80) {
System.out.println("B");
} else if (grade >= 70) {
System.out.println("C");
} else {
System.out.println("Needs support");
}switch
Matches one expression against constant cases. This is useful when checking exact values.
int day = 3;
switch (day) {
case 1:
System.out.println("Easy run");
break;
case 2:
System.out.println("Workout");
break;
case 3:
System.out.println("Recovery");
break;
default:
System.out.println("Plan later");
}if, else if, boolean expressions, and code tracing than on switch. Include switch as a useful Java structure, but do not let it replace AP-style if/else reasoning.2. Boolean Conditions: The Language of Decisions
A control structure is only as good as its condition. Students need to be able to read and build boolean expressions before they can write strong algorithms.
Relational Operators
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Logical Operators
&& and
|| or
! not
Common AP Trap: Chained Comparisons
int x = 7;
// Incorrect Java:
// if (0 < x < 10)
// Correct Java:
if (0 < x && x < 10) {
System.out.println("x is between 0 and 10");
}
Why is 0 < x < 10 wrong?
Java does not read chained inequalities like algebra. You must write two complete comparisons and join them with &&.
3. Iterative Statements: Looping
Iteration structures repeat a block of code until a termination condition is reached. Loops are where students begin thinking like algorithm designers.
for loop
Best when the number of iterations is known.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}Initialization, condition, and update are grouped in one line.
Enhanced for loop
Used to traverse arrays or collections without explicit indices.
int[] scores = {80, 92, 77};
for (int score : scores) {
System.out.println(score);
}This becomes more important in the arrays unit.
while loop
Best when the number of iterations is not known in advance.
int energy = 100;
while (energy > 0) {
energy -= 15;
System.out.println(energy);
}The condition is checked before each run.
do-while loop
Runs at least once because the condition is checked at the bottom.
int choice;
do {
choice = 1; // imagine user input here
System.out.println("Menu shown");
} while (choice != 1);Useful for menus and input validation.
4. Branching Statements: Jump Statements
Branching statements alter the normal flow. They are powerful, but students should use them intentionally because they can make code harder to trace.
break
Immediately exits the innermost loop or switch.
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
System.out.print(i + " ");
}What prints?
1 2 3. When i becomes 4, the loop stops immediately.
continue
Skips the rest of the current loop iteration and moves to the next cycle.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.print(i + " ");
}What prints?
1 2 4 5. The print statement is skipped only when i is 3.
return
Stops the current method and optionally sends a value back to the caller.
public static boolean isPassing(int grade) {
if (grade >= 70) {
return true;
}
return false;
}Why does this not need else?
If the first return runs, the method is finished. Otherwise, execution continues to return false;.
Try It in Java
Use the embedded compiler to run the examples below. Students should change the starting values, loop bounds, and conditions to test edge cases.
Core Algorithm Patterns
Once students understand the syntax, the real goal is to recognize patterns. These patterns show up constantly on AP multiple-choice questions and FRQs.
Counting
int count = 0;
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0) {
count++;
}
}
System.out.println(count);Count how many values meet a condition.
Accumulating
int total = 0;
for (int i = 1; i <= 5; i++) {
total += i;
}
System.out.println(total);Build a running sum or total.
Searching
boolean found = false;
for (int i = 1; i <= 10; i++) {
if (i * i == 49) {
found = true;
}
}
System.out.println(found);Check whether at least one value satisfies a condition.
Simulation
double height = 100.0;
int seconds = 0;
while (height > 0) {
height -= 9.8;
seconds++;
}
System.out.println(seconds);Update a changing value until a stopping condition occurs.
Common Unit 2 Mistakes
Mistake #1: Using separate if statements when only one category should print
int grade = 92;
if (grade >= 90) {
System.out.println("A");
}
if (grade >= 80) {
System.out.println("B");
}This prints both A and B. Use an else if ladder when categories are mutually exclusive.
Mistake #2: Off-by-one loop bounds
for (int i = 0; i <= 5; i++) {
System.out.println(i);
}This runs 6 times: 0, 1, 2, 3, 4, 5. Students often expect 5 times.
Mistake #3: Infinite loops
int x = 10;
while (x > 0) {
System.out.println(x);
}x never changes, so the condition stays true forever. A loop usually needs an update that moves it toward stopping.
Mistake #4: Accidental semicolon after a loop or if statement
while (x > 0); {
x--;
}The semicolon ends the loop immediately and creates an empty loop body. The block after it is not the loop body.
Mistake #5: Misreading break and continue
break exits the loop. continue skips only the rest of the current iteration and then keeps looping.
Code Tracing Practice
Students should trace these by hand before opening the answers.
Trace #1: What prints?
int x = 0;
for (int i = 1; i <= 4; i++) {
x += i;
}
System.out.println(x);Answer: 10. The loop adds 1 + 2 + 3 + 4.
Trace #2: What prints?
int n = 20;
int count = 0;
while (n > 2) {
n = n / 2;
count++;
}
System.out.println(count);Answer: 3. The values of n are 20 → 10 → 5 → 2, then the loop stops.
Trace #3: What prints?
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.print("E");
} else {
System.out.print("O");
}
}Answer: OEOEO.
Trace #4: What prints?
int total = 0;
for (int i = 1; i <= 6; i++) {
if (i == 4) {
continue;
}
total += i;
}
System.out.println(total);Answer: 17. It adds 1 + 2 + 3 + 5 + 6 and skips 4.
AP-Style Multiple Choice
1. Which loop is best when the number of iterations is known before the loop begins?
Answer: for loop.
2. Which expression correctly checks whether x is at least 10 and less than 20?
Answer: x >= 10 && x < 20
3. Which statement immediately exits a loop?
Answer: break
4. Which statement immediately exits a method?
Answer: return
5. What is the best reason to use a while loop?
Answer: Use it when the loop should continue until a condition changes, especially when you do not know the exact number of repetitions in advance.
FRQ Practice: Training Load Classifier
Write a method that classifies a workout based on distance and intensity. This is a control-structures FRQ because the method requires conditionals, boolean logic, and careful ordering.
/**
* Returns a workout classification based on distance and intensity.
* distanceMiles is the total distance of the workout.
* intensity is a value from 1 to 10.
*
* Return:
* "recovery" if distanceMiles < 4 and intensity <= 4
* "quality" if intensity >= 7
* "long" if distanceMiles >= 8
* "moderate" otherwise
*/
public static String classifyWorkout(double distanceMiles, int intensity) {
// write code here
}
Sample solution
public static String classifyWorkout(double distanceMiles, int intensity) {
if (distanceMiles < 4 && intensity <= 4) {
return "recovery";
} else if (intensity >= 7) {
return "quality";
} else if (distanceMiles >= 8) {
return "long";
} else {
return "moderate";
}
}The order matters. This solution gives priority to recovery first, then high-intensity quality days, then long runs.
Scoring guide
- Correct method signature and return type: 1 point
- Correct recovery condition using
&&: 2 points - Correct quality condition: 1 point
- Correct long condition: 1 point
- Correct default/moderate case: 1 point
- Uses
returncorrectly without unreachable or missing paths: 2 points - Readable and properly structured if/else logic: 2 points
Physics Simulation Mini-Lab: Projectile Safety Checker
This connects control structures to the physics simulation project. Students use selection and iteration to classify a projectile and explore how the launch angle affects range.
public class ProjectileSafetyChecker {
public static void main(String[] args) {
double speed = 22.0;
double g = 9.8;
for (int angle = 10; angle <= 80; angle += 10) {
double radians = Math.toRadians(angle);
double range = speed * speed * Math.sin(2 * radians) / g;
System.out.print("Angle: " + angle + " Range: " + range + " ");
if (range < 25) {
System.out.println("short");
} else if (range <= 45) {
System.out.println("target zone");
} else {
System.out.println("too far");
}
}
}
}
Student extension ideas
- Change the speed and observe how the classifications change.
- Add a variable for target distance and classify whether the projectile undershoots or overshoots.
- Track the best angle using a maximum-range algorithm.
- Replace the
forloop with awhileloop and compare readability.
Unit 2 Exit Ticket
Explain the difference between if, else if, and separate if statements.
if starts a decision. else if creates mutually exclusive follow-up choices. Separate if statements are independent, so more than one can run.
Explain when a while loop is a better choice than a for loop.
A while loop is usually better when the number of repetitions is not known before the loop starts and the loop should continue until some condition changes.
What are two signs that an algorithm has been designed well?
It handles edge cases and has clear stopping conditions. It should also be readable enough that another programmer can trace how values change.