Unit 2.1: Algorithms with Selection and Repetition
The three fundamental building blocks of all algorithms are:
- Sequencing: The default behavior where code runs line-by-line.
- Selection: Branching logic that runs code only if a condition is met.
- Repetition: Loops that run the same code multiple times.
- Sequencing: Executing statements one after another.
- Selection: Making decisions using conditional statements like
ifandswitch. - Repetition: Repeating actions using loops like
whileandfor.
This unit focuses on selection and repetition.
Selection
Selection allows a program to follow different paths based on whether a condition is true or false. In programming, we use selection to control the flow of our programs.
Task: Using an if-else statement for simple selection.
// Example of Selection
int temperature = 30;
if (temperature > 25) {
System.out.println("It's a hot day!");
} else {
System.out.println("It's a cool day.");
}
You will learn more about selection in the following sections.
Repetition (Iteration)
Repetition, also known as iteration or looping, is when a part of an algorithm is repeated a certain number of times or until a specific condition is met.
Task: Using a for loop for simple repetition.
// Example of Repetition
// This loop prints numbers 1 through 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
You will learn more about iteration in Part 2 of this unit.
The Importance of Order
The order in which you combine sequencing, selection, and repetition is critical to the correctness of your algorithm.
- The logical flow depends on the nesting of structures. A check before a loop determines if the loop runs at all, while a check inside a loop runs for every iteration.
Performing a check before a loop is different from performing it inside a loop.
Consider an algorithm to find the first even number in a list. You must first check if the list is empty (selection) before you start looping through it (repetition).
Task: Combining selection and repetition in a search algorithm.
import java.util.ArrayList;
public class OrderMatters {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Selection first: Check if the list is not empty before looping.
// If we tried to loop first, we might get an error on an empty list.
if (!numbers.isEmpty()) {
// Repetition: Loop through the numbers.
for (int num : numbers) {
// Selection: Check if the number is even.
if (num % 2 == 0) {
System.out.println("First even number found: " + num);
break; // Exit the loop
}
}
}
}
}