String Iteration and Indexing
The parameters determine which string is searched and which character is treated as a match.
A Count That Changes Selectively
Suppose you want to find how many times the letter a appears in banana. The important idea is not simply to increase a number repeatedly. Instead, the number increases only when the character currently being examined satisfies a condition. This selective updating is the counter pattern.
The counter pattern initializes a counter to 0, loops through data, checks a condition, and increments the counter when the condition is true.
A counter represents the number of matching events found so far. It changes on a successful match and remains unchanged when the condition is false.
Mapping Positions to Characters
When a loop examines banana, it visits each character in sequence: b, a, n, a, n, a. At every step, the program has a current character and can compare it with the target character a. The loop does not increment the counter merely because it moved to the next character; it increments only when the current character matches the target.
The position map shows why the loop must inspect every character. The target appears three times, but those matches are separated by nonmatching characters. A correct counter must preserve its current value during the nonmatching iterations and then increase when the next a is encountered.
Tracing the Counter
What do you think happens?
Before reading the trace, predict the counter value after each character in banana is examined while counting a.
Reveal answer
0, 1, 1, 2, 2, 3
The counter starts at 0. It stays unchanged for b and n, and increases by 1 for each of the three a characters.
The trace has two kinds of steps. When the current character is b or n, the comparison is false and count keeps its previous value. When the current character is a, the comparison is true and count increases by exactly 1. After all six characters have been examined, count is 3.
The Counting Process
A character-counting loop follows four actions in order: create the counter with value 0, read each character, test whether it equals the target, and increment the counter only after a successful comparison. The condition controls the state change. Without the condition, every character would be counted rather than only matching characters.
3The increment is indented inside the condition, so it runs only for a matching character. In this example, the three a characters trigger the increment, producing the final count 3.
Reusable Character Counting
Once the loop works, the same counter pattern can be placed inside a function. The function accepts the string to search and the character to count as parameters. This separates the counting process from one particular string or target, so the same logic can be reused with different inputs.
3
2The function keeps the same four-part process: initialize, iterate, test, and increment. The parameters determine which string is searched and which character is treated as a match. The return statement makes the accumulated count available to the caller.
Mistakes That Break the Count
Common mistake Initializing the counter inside the loop
What it looks likefor letter in text: count = 0Why it failsThe counter is reset during the iteration instead of accumulating across the characters.
Do this insteadInitialize the counter before the loop begins.
Common mistake Forgetting to increment the counter
What it looks likeif letter == target: passWhy it failsA matching character is recognized, but the accumulated total never changes.
Do this insteadIncrement the counter inside the true branch of the condition.
Common mistake Using assignment instead of comparison
What it looks likeif letter = target:Why it failsThe condition needs to compare the current character with the target character.
Do this insteadUse the comparison operator == for the match test.
Common mistake Placing the increment outside the condition
What it looks likeif letter == target: pass count = count + 1Why it failsThe counter increases for every loop iteration, including characters that do not match.
Do this insteadPlace the increment in the conditional block so only matches increase the total.
Practice the Trace
Trace the counter pattern for the string "cocoa" when the target character is "o". Write the counter value after each character is examined, then state the final count.
Hints
- Start the counter at 0.
- Keep the counter unchanged when the current character is not o.
- Increase it by 1 for each matching o.
Tracing cocoa
Count the occurrences of o in cocoa.
- 1Initialize
Set the counter to 0 before examining the string.
- 2Read c
c does not match o, so the counter remains 0.
- 3Read o
o matches the target, so the counter becomes 1.
- 4Read c
c does not match o, so the counter remains 1.
- 5Read o
o matches the target, so the counter becomes 2.
- 6Read a
a does not match o, so the counter remains 2.
The final count is 2.
Pattern Summary
- 1The counter pattern starts at 0, examines each item, checks a condition, and increments only when the condition is true.
- 2String character counting uses iteration to visit each character and comparison to identify matches.
- 3The counter remains unchanged during nonmatching iterations and accumulates the total number of matches.
- 4A function with string and target-character parameters turns one counting loop into a reusable tool.
- 5The same pattern can support other tasks that accumulate results based on a condition.
At a glance
- The counter pattern combines initialization, iteration, condition checking, and selective incrementing.
- To count a character, inspect every character and increment only when it matches the target.
- Tracing unchanged and changed counter values reveals how the final total is accumulated.
- A function can generalize the pattern by accepting the string and target character as parameters.