AP COMPUTER SCIENCE A • SELECTION AND ITERATION

Implementing Selection and Iteration Algorithms

Master the control structures that let programs make decisions and repeat actions with precision.

Historical Context & Motivation

Before high-level programming languages existed, early computer scientists had to wire hardware or punch machine-code instructions to make a computer branch or loop. The fundamental insight that programs could be composed entirely from sequence, selection, and iteration transformed software engineering from ad-hoc craft into a disciplined practice. These three control structures remain the backbone of every algorithm you will encounter on the AP Computer Science A exam and in professional development.

1843
Ada Lovelace's Notes
Ada Lovelace described the first algorithm for Charles Babbage's Analytical Engine, which included a loop to compute Bernoulli numbers — the earliest documented use of iteration in a program.
1946
Von Neumann Architecture
John von Neumann's stored-program concept introduced conditional branching at the hardware level, enabling selection logic through jump instructions based on register values.
1966
Structured Programming Theorem
Böhm and Jacopini proved that any computable function can be expressed using only sequence, selection (if-then-else), and iteration (while loops), eliminating the need for unstructured goto statements.
1995
Java Released
Sun Microsystems released Java with if, else, for, while, and do-while constructs baked into the language specification — the same constructs tested on the AP CS A exam today.

The core question that selection and iteration answer is simple yet profound: how does a program respond differently to different data and repeat work until a condition is met? Without these capabilities, every program would execute the same fixed sequence of statements regardless of input — useful for almost nothing.

Core Principles & Definitions

Selection and iteration are built on a small vocabulary of Java keywords and Boolean expressions. Understanding the precise semantics of each construct — when the condition is evaluated, which block executes, and how flow resumes — is essential for writing correct algorithms and tracing code on the AP exam.

1

Selection (if / else if / else)

Evaluates a Boolean expression and executes one of several code blocks. Only the first true branch in an if / else-if chain runs; the rest are skipped.
2

Iteration (for / while)

Repeats a block of code as long as a Boolean condition remains true. A for loop packages initialization, condition, and update in one header; a while loop tests only a condition.
3

Boolean Expressions

The guards that drive both selection and iteration. Composed of relational operators (<, >, <=, >=, ==, !=) and logical operators (&&, ||, !). Short-circuit evaluation applies.
4

Nested Structures

Selection and iteration can be nested to arbitrary depth. A loop may contain an if statement (filtering), and an if statement may contain a loop (conditional repetition).
5

Standard Algorithms

The AP CS A curriculum expects fluency with common patterns: finding a min/max, computing a sum/average, searching for a value, and determining if all or some elements satisfy a condition.
KEY TAKEAWAY
KEY TAKEAWAY

Visual Explanation — Control Flow

On the left, selection evaluates a condition once and branches; control merges afterward. On the right, iteration evaluates a condition repeatedly, executing the loop body each time it is true and looping back to re-check the condition.

The diagram above captures the fundamental difference between selection and iteration. In selection, the diamond (decision node) is visited exactly once: flow splits, one branch executes, and both paths merge into a single continuation. In iteration, the decision node is visited repeatedly — every time the loop body completes, an arrow feeds back to the condition. The loop terminates only when the condition evaluates to false. Recognizing this feedback arrow is critical: if the loop body never changes a variable used in the condition, you get an infinite loop.

How It Works — Syntax & Semantics

Selection Constructs

Java provides three levels of selection. A standalone if executes its body when the condition is true and does nothing otherwise. Adding else creates two mutually exclusive paths. Chaining else if clauses allows multi-way branching where only the first true condition's block runs. A common exam pitfall is using separate if statements instead of else if when the conditions are mutually exclusive — this causes multiple blocks to execute when only one was intended.

IF / ELSE IF / ELSE TEMPLATE
if (condA) { blockA } else if (condB) { blockB } else { blockC }
condA and condB are Boolean expressions. If condA is true, only blockA runs. If condA is false and condB is true, only blockB runs. If neither is true, blockC runs.

Iteration Constructs

The while loop checks its condition before each iteration; if the condition is initially false, the body never executes. The for loop compresses initialization, condition, and update into a single header, making it ideal for counted iteration. On the AP exam, do-while is not tested, but understanding that it checks the condition after the body runs helps solidify the concept. Every for loop can be rewritten as a while loop and vice versa — the choice is one of clarity, not capability.

FOR LOOP TEMPLATE
for (int i = start; i < end; i++) { body }
Executes body exactly (end − start) times when start < end. The variable i takes values start, start + 1, …, end − 1.
EQUIVALENT WHILE LOOP
int i = start; while (i < end) { body; i++; }
Identical behavior: initialization before the loop, condition checked each iteration, update at the end of the body.
Off-By-One Errors

Standard Algorithms — The Exam Essentials

The College Board specifies a set of standard algorithms that combine selection and iteration in predictable patterns. Mastering these patterns lets you recognize them quickly in MCQs and produce them reliably in FRQs. The table below catalogs each algorithm, its typical structure, and a key implementation detail.

Standard selection-and-iteration algorithms tested on AP CS A
AlgorithmPatternKey Detail
Find Minimum / MaximumInitialize to first element; iterate and compare with ifInitialize to arr[0], not Integer.MAX_VALUE, to handle negative arrays safely.
Compute Sum / AverageAccumulator variable updated inside a loopUse double for average to avoid integer division.
Linear SearchLoop with an if that returns index on matchReturn −1 after the loop to signal "not found".
Check All / Check AnyBoolean flag + loop; for "all", start true and set false on failureFor "any", start false and set true on success. Return early when possible.
Count OccurrencesCounter variable incremented inside a conditionalUse .equals() for Strings, == for primitives.
The trace table shows each iteration of the find-maximum algorithm. The variable max is initialized to arr[0] = 3, then updated each time a larger element is found. The amber-highlighted element (9) is the final maximum.

Worked Example — Counting Even Numbers

Write a method countEvens that accepts an array of integers and returns the number of even values. This combines iteration (traversing the array) with selection (testing each element).

1
Step 1 — Declare the method and accumulatorWe need a method that takes an int[] parameter and returns an int. Declare a counter variable initialized to 0.
public static int countEvens(int[] arr) { int count = 0;
2
Step 2 — Iterate through the arrayUse a for loop from index 0 to arr.length - 1. This guarantees every element is visited exactly once.
for (int i = 0; i < arr.length; i++)
3
Step 3 — Apply the selection conditionInside the loop, check whether arr[i] % 2 == 0. The modulus operator returns the remainder of division by 2. If the remainder is 0, the number is even. Increment count when the condition is true.
if (arr[i] % 2 == 0) { count++; }
4
Step 4 — Return the resultAfter the loop completes, count holds the total number of even elements. Return it.
return count; }
5
Step 5 — Trace with sample inputFor arr = {3, 8, 5, 12, 7}: i=0 → 3%2≠0, i=1 → 8%2==0 (count=1), i=2 → 5%2≠0, i=3 → 12%2==0 (count=2), i=4 → 7%2≠0. The method returns 2.
countEvens({3, 8, 5, 12, 7}) → 2

for vs. while — When to Use Which

Since for and while loops are interchangeable in power, the choice is about readability and intent. The table below summarizes the conventional guidelines.

Criterionfor loopwhile loop
Number of iterationsKnown in advance (e.g., array length)Unknown; depends on runtime condition
Loop variable scopeDeclared in header; scoped to the loopDeclared before loop; persists after
Typical use caseArray traversal, countingSentinel-controlled input, searching until found
Risk of infinite loopLower — update is in the headerHigher — developer must remember to update
AP Exam frequencyVery common in array/String traversal MCQsCommon in FRQs involving user input or search
KEY TAKEAWAY
CHOOSE WISELY

Connection to Advanced Topics

Selection and iteration are the building blocks for nearly every advanced algorithm in computer science. The techniques you learn here scale directly into topics such as nested loops for 2D arrays, recursion (which replaces explicit iteration with self-referential method calls), and sorting algorithms that combine both selection and iteration in sophisticated ways.

This LessonAdvanced Extension
Single for loop traversing an arrayNested for loops traversing a 2D array (row-major order)
Linear search with early returnBinary search requiring a sorted array and logarithmic time
Find max using a single passSelection sort: repeatedly find min of unsorted subarray
while loop with a condition variableRecursion: the "condition" becomes the base case, the "loop back" becomes the recursive call

On the AP exam, FRQ questions frequently ask you to write methods that involve iterating through an ArrayList while conditionally removing or modifying elements. This is a direct application of combining iteration with selection, and it introduces the subtlety that removing an element during forward traversal can skip the next element. Traversing backward or adjusting the index after removal solves this — a detail the exam loves to test.

Practice Problems

1
Consider the following code segment: int x = 10; if (x > 5) x -= 3; if (x > 5) x -= 3; System.out.println(x); What is printed? A) 10 B) 7 C) 4 D) 3
2
What is the output of the following code? int sum = 0; for (int i = 1; i <= 5; i++) { if (i % 2 != 0) sum += i; } System.out.println(sum); A) 6 B) 9 C) 15 D) 10
3
Consider the following method: public static String mystery(String str) { String result = ""; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + 1).equals("a")) result += "@"; else result += str.substring(i, i + 1); } return result; } What does mystery("banana") return? A) "b@n@n@" B) "b@nana" C) "ban@n@" D) "@@@@@@"
PROBLEM 4APPLIED
Write the method public static int indexOfMax(int[] arr) that returns the index of the maximum value in arr. If there are duplicate maximum values, return the index of the first occurrence. You may assume arr has at least one element.
PROBLEM 5CRITICAL THINKING
Write the method public static boolean isStrictlyIncreasing(int[] arr) that returns true if every element is strictly greater than the one before it, and false otherwise. An array with 0 or 1 elements is considered strictly increasing.
Varsity Tutors • AP Computer Science A • Implementing Selection and Iteration Algorithms