01 / 21

Selection & Iteration
Algorithms

Master the building blocks of programming: conditional logic and loop structures that power every Java application.

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. In Java, algorithms are built from three fundamental control structures: sequence, selection, and iteration.

Sequence
Statements execute one after another, top to bottom.
Selection
Choose which statements to execute based on a condition.
Iteration
Repeat statements while a condition remains true.

Selection: Branching Logic

Selection statements let your program make decisions. Java evaluates a boolean expression and executes different code blocks depending on whether the result is true or false.

condition? boolean if body true else body false continue

Iteration: Loop Structures

Iteration repeats a block of code while a condition holds true. Java provides three main loop constructs, each suited to different situations.

while loop
Tests condition before each iteration. May execute zero times if condition is initially false.
for loop
Combines init, condition, and update in one line. Ideal when the number of iterations is known.
for-each loop
Iterates over every element of an array or collection. Cannot modify index or skip elements.

The while Loop Pattern

int count = 0; while (count < 5) { System.out.println(count); count++; }
count = 0 count < 5? true print; count++ loop back false exit loop

The for Loop Pattern

for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
1
Init: int i = 0 : executed once before the loop starts.
2
Test: \(i < \text{arr.length}\) : checked before every iteration.
3
Update: i++ : executed after the loop body each time.

Core Rule: Nesting Selection Inside Iteration

The real power emerges when you combine selection and iteration. A loop traverses data, and an if statement inside the loop filters, counts, or transforms each element conditionally.

// Count positive numbers in an array int count = 0; for (int num : arr) { if (num > 0) { count++; } } System.out.println("Positives: " + count);

while vs for: When to Use Each

while loop for loop
Iterations known? Not necessarily Usually known
Init / Update Separate statements Built into header
Use case Sentinel values, user input Array traversal, counting
Off-by-one risk Higher (manual update) Lower (compact header)
Infinite loop risk Higher (forget update) Lower

How to Implement an Algorithm

1
Identify the task: What are you computing? (Sum, max, count, search, filter?)
2
Choose data structure: Array, ArrayList, or single variables?
3
Pick the loop type: Use for when count is known, while for sentinel-controlled, for-each for read-only traversal.
4
Add selection inside: Use if / else if / else to handle conditions on each element.
5
Trace and test: Manually trace through 2-3 iterations to verify correctness and edge cases.

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]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; }

Example 2: The Accumulator Pattern

Compute the average of all even numbers in an array.

int sum = 0, count = 0; for (int num : arr) { if (num % 2 == 0) { sum += num; count++; } } double avg = (double) sum / count;

Example 3: Nested Iteration

Check if an array contains any duplicate values using nested loops.

public static boolean hasDuplicates(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] == arr[j]) { return true; } } } return false; }

Example 4: String Traversal

Count the number of vowels in a given String.

public static int countVowels(String s) { int count = 0; String vowels = "aeiouAEIOU"; for (int i = 0; i < s.length(); i++) { if (vowels.indexOf(s.charAt(i)) != -1) { count++; } } return count; }

Sentinel-Controlled Loops

A sentinel value is a special input that signals the loop to stop. This pattern uses a while loop because the number of iterations is unknown in advance.

Scanner sc = new Scanner(System.in); int total = 0; int input = sc.nextInt(); while (input != -1) { // -1 is the sentinel total += input; input = sc.nextInt(); }

Common Mistakes

✕ Infinite Loop
Forgetting to update the loop variable inside a while loop causes it to run forever.
✕ Off-by-One
Using \(\le\) instead of \(<\) with arr.length causes an ArrayIndexOutOfBoundsException.
✕ Misplaced Selection
Placing an if statement outside the loop when it should be inside, causing it to check only the last element.
✕ Using == on Strings
Comparing Strings with \(==\) checks reference equality, not content. Use .equals() instead.
✕ Modifying During For-Each
The loop variable is a copy. Reassigning it (e.g., num = 0) won't change the original array. For objects, you can still modify the object's state via its methods.

Algorithm Patterns Summary

Pattern Loop Type Selection Example
Find max/min for if (comparison) Largest value
Count/filter for-each if (test) Count evens
Accumulate for-each if (qualify) Sum positives
Search for / while if (match) Find index
Sentinel input while if (validate) Read until -1
Duplicate check nested for if (\(==\)) Any repeats?

Question 1 of 5

What is printed when this code segment is executed?

Question 2 of 5

Which loop type is most appropriate when the number of iterations is not known before the loop begins?

Question 3 of 5

What value is printed?

Question 4 of 5

What value of count is printed?

Question 5 of 5

What is the main risk of placing the loop variable update inside an if statement within a while loop?