01 / 21

Algorithms with
Selection & Repetition

Master the building blocks of program logic: if/else decisions, loop structures, and how to combine them to solve problems algorithmically.

AP Computer Science A

What Is an Algorithm?

An algorithm is a finite, step-by-step procedure for solving a problem or performing a computation. Every Java program you write encodes an algorithm: a precise sequence of instructions the computer follows.

Algorithms gain their power from two key control structures: selection (choosing different paths) and repetition (looping until a condition is met).

Selection: Making Decisions

Selection statements let your program choose between paths based on a Boolean condition. In Java, the primary selection constructs are if, if/else, and if/else if/else.

Start Condition true? true Action A false Action B Continue

Repetition: Looping Structures

Repetition statements execute a block of code multiple times as long as a Boolean condition holds. Java provides three loop types, each suited to different scenarios.

while Loop
Tests condition before each iteration. May execute zero times if condition is initially false.
for Loop
Compact syntax: init, condition, update in one line. Ideal when the number of iterations is known.
for-each Loop
Iterates over every element in an array or collection. No index variable needed: read-only traversal.

Core Rule: Boolean Expressions

Every selection and loop in Java is controlled by a Boolean expression: an expression that evaluates to true or false. Understanding these is the key to controlling program flow.

1
Relational operators: ==, !=, <, >, <=, >= compare two values and return a boolean.
2
Logical operators: && (AND), || (OR), ! (NOT) combine or negate Boolean values.
3
Short-circuit evaluation: Java evaluates && and || left to right and stops as soon as the result is determined.

Anatomy of if / else if / else

if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else { grade = "F"; }

Key insight: Order matters. If we checked score >= 70 first, a score of 95 would incorrectly get "C" instead of "A".

Anatomy of while and for Loops

while loop
int i = 0;
while (i < 5) {
  System.out.print(i);
  i++;
}
// 01234
for loop
for (int i = 0; i < 5; i++) {
  System.out.print(i);
}

// 01234

Key Distinction: Choosing the Right Loop

while for for-each
Iterations known? Not necessarily Usually yes All elements
Condition tested Before each pass Before each pass Automatic
Index access? Yes (manual) Yes (built-in) No
Can modify array? Yes Yes Not safely
Best for Sentinel loops, input Counting, indexed ops Read-only traversal

How to Write an Algorithm

1
Identify the problem. What input do you have? What output do you need?
2
Determine if selection is needed. Does the logic branch based on a condition? Use if/else.
3
Determine if repetition is needed. Does a block of code repeat? Choose while, for, or for-each.
4
Trace through edge cases. What happens with \(n = 0\)? Empty arrays? Negative values?
5
Verify termination. Every loop must have a condition that eventually becomes false, or the program will loop forever.

Example 1: Find the Maximum

Given an array of integers, find and return the largest value.

public static int findMax(int[] arr) { int max = arr[0]; // assume first is max for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { // selection inside loop max = arr[i]; } } return max; }

Example 2: Count Even Numbers

public static int countEvens(int[] arr) { int count = 0; for (int val : arr) { // for-each loop if (val % 2 == 0) { // selection count++; } } return count; }

Trace with arr = {3, 8, 5, 12, 7}:

val val % 2 == 0? count
3false0
8true1
5false1
12true2
7false2

Example 3: Classify Temperatures

Print a label for each temperature in an array: cold, warm, or hot.

for (int temp : temps) { if (temp < 50) { System.out.println(temp + " Cold"); } else if (temp < 80) { System.out.println(temp + " Warm"); } else { System.out.println(temp + " Hot"); } }

For temps = {30, 65, 90}, the output is: 30 Cold, 65 Warm, 90 Hot.

The Sentinel Loop Pattern

A sentinel loop repeats until a special value (the sentinel) is encountered. This is the classic use case for a while loop because the number of iterations is unknown.

Scanner in = new Scanner(System.in); int sum = 0; int val = in.nextInt(); while (val != -1) { // -1 is the sentinel sum += val; val = in.nextInt(); } System.out.println("Sum: " + sum);

Visualizing Loop + Selection

max = arr[0], i = 1 i < arr.length? false return max true arr[i] > max? true max = arr[i] i++

Common Mistakes to Avoid

Infinite Loop
Forgetting to update the loop variable (e.g., missing i++) causes the condition to remain true forever.
Off-by-One Error
Using <= instead of < (or vice versa) causes the loop to execute one too many or one too few times.
== with Strings
Using == to compare Strings checks reference equality, not content. Always use .equals().
Dangling else
An else binds to the nearest if. Without braces, the structure may not match your intent.
Unreachable Code
Placing conditions in the wrong order (e.g., checking >= 70 before >= 90) makes later branches unreachable.

Summary: Selection vs. Repetition

Selection Repetition
Purpose Choose a path Repeat a block
Keywords if, else if, else while, for, for-each
Executes body At most once per branch Zero or more times
Controlled by Boolean expression Boolean expression
Nesting Can contain loops Can contain if/else
AP focus Multi-way branching Array traversal, accumulation

Question 1 of 5

What is printed when this code executes?

Question 2 of 5

What value is printed?

Question 3 of 5

Which loop is most appropriate when you need to traverse an array without modifying it and you do not need the index?

Question 4 of 5

What happens when this code executes?

Question 5 of 5

What value is printed?