📓2.9: Implementing Selection & Iteration Algorithms
Table of Contents
📖 This page is a condensed version of CSAwesome Topic 2.9
Loops are not just for counting — they can perform many common algorithmic patterns, such as accumulating totals, finding maximums, or searching for a value.
Accumulator Pattern
An accumulator keeps a running total as the loop iterates.
Coding Exercise: Sum 1 to 5
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println("Sum is " + sum);
Counter Pattern
A counter counts how many times something happens.
Coding Exercise: Count Even Numbers
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
count++;
}
}
System.out.println("Number of even integers: " + count);
Finding the Maximum
Coding Exercise: Largest Number in Array
int[] nums = {5, 9, 2, 7, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
System.out.println("Max is " + max);
Searching for a Value
Coding Exercise: Search Array for Target
int[] nums = {3, 6, 9, 12};
int target = 9;
boolean found = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
found = true;
}
}
System.out.println("Found? " + found);
Summary
- Accumulator: running total.
- Counter: counts matches.
- Maximum finder: tracks largest value.
- Search: checks for target presence.
AP Practice
Question 1</summary>
What will this print?
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += i;
}
System.out.println(sum);
Answer: 6
— because 0 + 1 + 2 + 3 = 6
.
</details>
Question 2</summary>
What does this code do?
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
count++;
}
}
System.out.println(count);
Answer: Counts the odd numbers from 1 to 10, so it prints 5
.
</details>
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += i;
}
System.out.println(sum);
6
— because 0 + 1 + 2 + 3 = 6
. Question 2</summary>
What does this code do?
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
count++;
}
}
System.out.println(count);
Answer: Counts the odd numbers from 1 to 10, so it prints 5
.
</details>
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
count++;
}
}
System.out.println(count);
5
.