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.
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.
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.
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.
==, !=, <, >, <=, >= compare two values and return a boolean.&& (AND), || (OR), ! (NOT) combine or negate Boolean values.&& and || left to right and stops as soon as the result is determined.Anatomy of if / else if / else
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 (i < 5) {
System.out.print(i);
i++;
}
// 01234
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
Example 1: Find the Maximum
Given an array of integers, find and return the largest value.
Example 2: Count Even Numbers
Trace with arr = {3, 8, 5, 12, 7}:
| val | val % 2 == 0? | count |
|---|---|---|
| 3 | false | 0 |
| 8 | true | 1 |
| 5 | false | 1 |
| 12 | true | 2 |
| 7 | false | 2 |
Example 3: Classify Temperatures
Print a label for each temperature in an array: cold, warm, or 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.
Visualizing Loop + Selection
Common Mistakes to Avoid
i++) causes the condition to remain true forever.<= instead of < (or vice versa) causes the loop to execute one too many or one too few times.== to compare Strings checks reference equality, not content. Always use .equals().else binds to the nearest if. Without braces, the structure may not match your intent.>= 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
Consider the following code segment:
int x = 7;
if (x > 10) {
System.out.print("A");
} else if (x > 5) {
System.out.print("B");
} else {
System.out.print("C");
}
What is printed when this code executes?
x > 10 is false. The second condition x > 5 is true, so "B" is printed. The else branch is skipped.Question 2 of 5
Consider the following code segment:
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
System.out.print(sum);
What value is printed?
i <= 5, the answer would be 15.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
Consider the following code segment:
int k = 0;
while (k < 10) {
System.out.print(k + " ");
}
What happens when this code executes?
k < 10 remains true forever. This is a classic infinite loop error: always ensure the loop variable is updated.Question 5 of 5
Consider the following code segment:
int[] arr = {5, 12, 3, 8, 1};
int count = 0;
for (int val : arr) {
if (val > 4) {
count++;
}
}
System.out.print(count);
What value is printed?