For Loops and Loop Control
The counter pattern is a fundamental computational technique: initialize a counter to 0, loop through data, check a condition, and increment the counter when the condition is true.
One Question, Many Matches
Suppose you need to answer a simple question: how many times does the letter a appear in banana? The answer is 3, but the useful programming idea is how to arrive at that answer. A loop can examine each character, a condition can decide whether the character matters, and a counter can remember how many matches have been found so far.
The counter pattern records a running total. It starts at 0, examines data repeatedly, and increases only when the current item satisfies a condition.
Tracing Banana Character by Character
What do you think happens?
Before reading the trace, predict the counter value after each character in banana is examined while counting the letter a.
Reveal answer
Answer: 0, 1, 1, 2, 2, 3
The counter begins at 0. It increases at the second, fourth, and sixth characters because those positions contain a.
| Position | Character | Matches a? | Counter after checking |
|---|---|---|---|
| 0 | b | No | 0 |
| 1 | a | Yes | 1 |
| 2 | n | No | 1 |
| 3 | a | Yes | 2 |
| 4 | n | No | 2 |
| 5 | a | Yes | 3 |
The counter changes only at positions containing the target character.
The important observation is not merely that the final count is 3. The counter changes selectively. It stays unchanged for b, n, and n. It increases by exactly 1 for each a. This selective update is the central behavior of the counter pattern.
The Four-Part Counter Pattern
- Initialize the counter to 0 before the loop begins.
- Use a for loop to examine each item in the data.
- Check whether the current item satisfies the condition.
- Increment the counter when the condition is true.
- Use the counter after the loop to obtain the accumulated result.
Initialization gives the counter a known starting state. Iteration supplies one character at a time. The condition separates matching characters from non-matching characters. Conditional incrementing ensures that only successful matches contribute to the result.
3Following the Counter State
A useful tracing habit is to write down the counter after every iteration. For banana, the sequence is 0, 1, 1, 2, 2, 3. The repeated values are meaningful: they show that the loop examined a character that did not satisfy the condition. A counter does not need to change on every iteration.
When debugging a counter loop, record three values for each iteration: the current character, whether the condition is true, and the counter after the condition is processed. This makes it easier to locate an incorrect increment or an incorrect comparison.
From One Loop to a Reusable Function
Once the loop works for one string and one target character, the same logic can be encapsulated in a function named count. The function accepts the string to search and the letter to count as two arguments. This separates the reusable counting process from the particular values supplied by a caller.
3The function keeps the counter local to the counting task, examines each character in the supplied string, and returns the accumulated result. Changing the arguments lets the same pattern count a different character in a different string without rewriting the loop.
Mistakes That Break the Count
Initializing the counter inside the loop
Earlier matches are erased instead of accumulated.
Fix:
Initialize the counter to 0 before the loop begins.Forgetting to increment the counter
The loop detects matches without recording them, so the accumulated result cannot grow.
Fix:
Increment the counter inside the conditional branch that handles a true match.Using assignment instead of comparison
The condition needs to test whether two values are equal.
Fix:
Use == for the character comparison described by the pattern.Placing the increment outside the if block
Non-matching characters are counted as though they satisfied the condition.
Fix:
Place the increment inside the if block so only matching characters contribute.
Practice the Pattern
Write a function named count that accepts two arguments: a string to search and a target character. Use the counter pattern to count how many times the target appears. Test your function with banana and a, then trace the counter after each character.
Hints
- Create the counter before the loop and set it to 0.
- Use the for loop variable as the current character.
- Compare the current character with the target using ==.
- Increment only when the comparison is true.
- Return the counter after all characters have been examined.
Pattern Summary
- The counter pattern starts by initializing a counter to 0.
- A for loop examines each item in the data, and an if statement checks whether it matches the target condition.
- The counter changes only when the condition is true; it remains unchanged when the condition is false.
- Counting characters in a string is a direct application of this pattern.
- A function with string and target-character parameters turns the counting logic into a reusable tool.
Key Takeaways
- The counter pattern combines initialization, iteration, conditional checking, and selective incrementing.
- For banana, the counter increases at the three positions containing a and ends at 3.
- Tracing the counter after every iteration reveals why it changes or stays the same.
- Encapsulating the pattern in a count function makes it reusable for different strings and target characters.