Searching an Array
Whole-array problems are solved by visiting every element with a for loop and combining what you find.
Questions That Need the Whole Array
Once you can store many values in one array, the next question is usually about the array as a whole. What is the typical value of the numbers stored there? Which one is the biggest? Neither question can be answered by looking at a single element. Each one requires visiting every position in the array and combining what you find along the way.
The two classic whole-array problems in this article are finding the average of all the elements and finding the largest element. Both are solved with a for loop, and both follow a pattern you will reuse many times: keep a small amount of running information, update it as you move through the array, and read the answer once the loop finishes.
Tracing a Running Sum Through the Array
Suppose A is an array of doubles and you want its average. The approach has two stages. First, a for loop adds up every number in the array. Second, the total is divided by the length of the array. The result is the average. Follow the first stage with a small array, A = [4, 11, 7, 2]. The loop keeps a single variable, total, that starts at 0. On each pass it adds the current element to total, so total grows from 4 to 15 to 22 to 24 as the loop visits each position.
Only total changes while the loop runs. Each element enters the calculation exactly once, and the loop never needs to look back at earlier elements. When the loop ends, total holds 24, the sum of every element in the array.
Dividing Only After the Loop Finishes
An average is computed by summing every element and dividing by the array length after the loop finishes. The loop only does the adding. The division happens once, at the end. This separation is deliberate. Dividing inside the loop would produce a wrong answer, because you would be dividing partial totals instead of the complete sum.
6.0- The loop body contains only the addition.
len(A)gives the number of elements, 4.- The division uses the complete total, 24, after the loop has ended.
Carrying the Largest Value Forward
A second common task is to find the largest number in an array. The strategy is to walk through the array while remembering the largest value seen so far. That remembered value is stored in a variable, which this course calls max. Whenever the loop meets an element larger than the current value of max, max is updated to that larger element. The loop does not need to remember anything else.
Notice that the answer is not known in advance. It is built up one comparison at a time, and only the final state of max reveals the result. In the array above, max is replaced once, when 11 is met, and then survives the remaining comparisons unchanged.
11max_valuestarts at A[0], which is 4.- A[1:] visits the remaining elements, starting from A[1].
- The if statement replaces
max_valueonly when a larger element appears.
Why the Starting Value of max Matters
A question remains before the loop can start: what should max contain at the beginning? Whatever you choose must be a value that the array can actually provide, or the comparison logic will not behave correctly. One reasonable choice is to start max at the first element, A[0], and then examine the remaining elements starting from A[1]. Because the first element is already in max, the loop only needs to compare against the rest of the array. This choice guarantees that max begins with a value that really is in the array.
What do you think happens?
If max starts at 0 and the array is B = [-5, -2, -8], what will max contain when the loop finishes?
Reveal answer
0
No element is larger than 0, so the comparisons never replace max. It keeps its starting value of 0, even though 0 is not an element of the array. The largest element is actually -2.
Mistakes Beginners Make with Running Values
Common mistake Dividing the running total inside the loop
What it looks likeFor A = [4, 11, 7, 2], writing total = total / len(A) on each pass gives a final value of 1.125.
Why it failsEach pass divides the partial total, so the division shrinks the sum repeatedly instead of dividing the complete sum once.
Do this insteadAdd inside the loop and divide once after the loop: average = total / len(A). This gives 6.0 for the same array.
Common mistake Starting max at 0 for an array that may contain negative numbers
What it looks likeFor B = [-5, -2, -8], a starting max of 0 ends with max equal to 0.
Why it fails0 is not an element of the array, and no element is larger than it, so it is never replaced.
Do this insteadStart max at A[0] and compare the remaining elements. The result is -2.
Common mistake Forgetting to update the tracking variable inside the if statement, so the loop compares elements but never changes max
Practice Tracing the Maximum
Given C = [-3, -10, -1, -7], trace the running-maximum method with max starting at C[0]. Record the value of max after each comparison and state the final result.
Hints
- Start with max equal to -3.
- Replace max only when the current element is larger than max.
- Remember that -1 is larger than -3, and -1 is larger than -7.
Summary of the Two Whole-Array Patterns
- 1Whole-array questions are answered by visiting every element with a for loop and combining what is found.
- 2To compute an average, add all elements in the loop and divide by the array length once, after the loop finishes.
- 3To find the largest element, keep a running max, replace it when a larger element appears, and read the final value after the loop.
- 4Start max at A[0] so its starting value is always an element of the array, which keeps the comparisons correct.
At a glance
- A single for loop can sum every element of an array, and dividing that sum by the array length after the loop gives the average.
- The running-maximum strategy keeps one tracking variable, max, and replaces it whenever a larger element is found.
- Starting max at A[0] ensures its initial value is a real element of the array, so arrays of negative numbers are handled correctly.
- Division belongs after the loop, because dividing partial totals inside the loop gives a wrong answer.