AP® Computer Science A · Unit 4 · Topic 4.5

Counting, Any, and All over an Array

Counting, any, and all are three patterns for scanning an array: count tallies every match, any stops early at the first success, and all stops early at the first failure.

These three patterns all walk through an array once, but they stop for different reasons. A counting loop never quits early: it checks every element against a condition and increments a counter each time the condition is true, because you need to see the whole array to know the total. An 'any' loop is impatient: it returns true the instant it finds one element that matches, because one success is enough to answer 'does at least one qualify?' You only reach the end and return false if nothing ever matched. An 'all' loop is also impatient, but in the opposite direction: it returns false the instant it finds one element that breaks the rule, because a single failure ruins the claim that every element qualifies. You only return true if the loop finishes with no failures found.

The reason you don't always need to look at every element comes down to what question you're asking. 'Any' and 'all' are existence questions — one piece of evidence, for or against, settles them. Counting is a tally question — missing even one element could change the answer, so there's no shortcut.

This topic sets up everything else in the unit. Searching an array for a target value is really an 'any' check with a twist: instead of just true or false, you report where the match was. Comparing consecutive pairs — used in checking if an array is sorted — reuses the same early-exit logic as 'all', just applied to arr[i] and arr[i+1] instead of a single element.

Key terms

Early exit
Stopping a loop as soon as the answer is certain, used by any and all checks but not counting.
Any check
A loop that returns true the moment one element satisfies a condition, and false only if none ever do.
All check
A loop that returns false the moment one element fails a condition, and true only if none ever fail.
Counting loop
A loop that examines every element and increments a tally each time a condition is met.
Consecutive pair
Two adjacent elements, arr[i] and arr[i+1], compared together rather than checked individually.

Watch it explained

  1. How it worksHow does a counting loop differ from a loop that stops the moment it finds a match?
  2. Worked exampleFind how many elements of {3, 8, 12, 5, 20} are greater than 6.
  3. Worked exampleTrace a check that every element of {2, 4, 6, 7} is even and find where it fails.
  4. Common mistakeWhy doesn't a loop that returns true from inside the body correctly test all elements?
  5. Going furtherWhat changes when the algorithm needs consecutive pairs instead of single elements?

Check yourself

Your turn1 of 2
An algorithm needs to examine every CONSECUTIVE PAIR of elements in an array of length 35 (comparing element i to element i+1). How many such pairs are there?

End of topic.