Common Iteration Patterns: Searching and Accumulating
You'll learn how to use loops to find specific elements and compute aggregate values like sums and averages.
When working with arrays, two patterns come up constantly: searching for an element and accumulating values. These are the bread and butter of array processing.
Searching for an Element
Searching means iterating through an array until you find what you're looking for (or reach the end). You typically use a flag variable or return early when found:
int[] numbers = {4, 7, 2, 9, 5};
int target = 9;
int foundIndex = -1; // -1 means "not found"
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
foundIndex = i;
break; // Stop searching once found
}
}
Think of it like scanning a bookshelf for a specific title—you stop when you find it.
Accumulating Values
Accumulating means building up a result across all elements. Common examples include summing values, counting matches, or finding the maximum:
int[] scores = {85, 92, 78, 90, 88};
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum = sum + scores[i]; // Accumulate the total
}
int average = sum / scores.length;
You start with an initial value (often 0 for sums, -1 for max searches) and update it with each element. It's like filling a bucket drop by drop.
Why These Matter
Almost every real-world array operation uses one of these patterns. Finding a customer by ID? Searching. Calculating total sales? Accumulating. Mastering these two techniques unlocks countless practical applications.
Key Takeaway: Searching iterates until finding a match (often using break), while accumulating builds a result across all elements using an updatable variable.