Loop-and-count problems (J2 pattern)
- Module
- M3.2
- Lesson
- 1 of 1
- Reading time
- 5 min
In this lesson
- Read multiple items in a loop and accumulate a count or total.
- Initialize a counter before the loop and update it inside.
- Use the final count to make a decision or produce output.
Many problems ask you to read a list of items, count how many meet a condition, and then output the result. This is the loop-and-count pattern. It builds on what you learned about loops in M1.6 and accumulators in M2.4.
The pattern: counter before, update inside
To count items, you need a variable that starts at zero and increments each time you find a match. The key is to initialize the counter outside the loop, before you start reading items.
Imagine a problem where you read the marks of several students and count how many pass (50 or higher). You do not know how many students there are at first, but the problem tells you. Read that number, then loop that many times, and count as you go.
The counter is a running total. Each time you see a passing mark, add one to the counter. After the loop ends, print the counter.
n = int(input())passing_count = 0
for i in range(n): mark = int(input()) if mark >= 50: passing_count += 1
print(passing_count)Here n is the number of students. passing_count starts at zero. Inside the loop, each mark is read. If it is 50 or higher, we add one to passing_count. When the loop ends, we print the count.
Trace this on a small example: five students with marks 45, 68, 51, 50, and 49. The first mark, 45, is under 50, so passing_count stays 0. The next mark, 68, is 50 or higher, so passing_count becomes 1. Marks 51 and 50 each add one more, taking it to 2 and then 3. The last mark, 49, is under 50 again, so passing_count stays 3.
The output is 3.
n = int(input())passing_count = 0
for i in range(n): mark = int(input()) if mark >= 50: passing_count += 1
print(passing_count)Input
5
45
68
51
50
49Output
3Accumulation, not replacement
A common mistake is to set the counter inside the loop instead of incrementing it. If you write passing_count = 1 when you find a passing mark, you lose the count of all the previous passes: the count resets to one instead of growing by one. The operator += means "add to the existing value", not "replace", and that is the difference between accumulating and overwriting.
Another mistake is to forget to initialize the counter before the loop. If passing_count does not exist when you first try to increment it, Python stops with an error. Always initialize accumulators to 0 before the loop.
Conditions inside the loop
The condition that decides whether to count can be anything. You might count items that match a threshold, like marks of 50 or higher. You might count items that belong to a category, like grades that are "A". You might count items that fall within a range, like times between 8 and 17 (business hours).
The loop itself only repeats; it does not decide anything on its own. The logic lives in the if statement. Write the condition that identifies the item you want to count, and increment the counter when it is true.
n = int(input())vowel_count = 0
for i in range(n): word = input() if word[0] in "aeiouAEIOU": vowel_count += 1
print(vowel_count)This example counts how many words start with a vowel. The condition word[0] in "aeiouAEIOU" checks whether the first character is a vowel. When it is true, the count increments.
Multiple counters
Sometimes a problem asks you to count different things. You might count passing marks, failing marks, and absences. Use one counter for each thing you track. Initialize all of them before the loop, then update each one based on the item you read.
n = int(input())high = 0low = 0
for i in range(n): score = int(input()) if score > 75: high += 1 else: low += 1
print(high, low)This counts how many scores exceed 75 and how many do not. Each counter accumulates separately, and both are printed at the end.
After the loop
Once the loop exits, the counter holds the final count. You can use it to produce output, make a decision, or compute a final result. A loop-and-count problem typically reads items, counts them, and then prints the count or a message based on the count.
Some problems ask for more than just the count. You might print the count and some text, like "5 students passed the test". Write the count and the text exactly as the problem asks, using print statements.
If the problem asks a yes/no question based on the count, use the count in a final if statement to decide what to output.
Why this pattern works
Counting requires two pieces: a place to hold the total and a way to update it. The counter variable holds the total, and the += operator updates it by adding one each time the condition is true. Without storing the count, you would need to remember every matching item instead of just a running number. This pattern stays fast no matter how many items you count, because it uses one integer, not a growing structure.
Another example: counting increases
Loop-and-count is not limited to numbers you read one at a time. It works just as well on a list you already have in memory. Suppose you read a list of numbers and want to know how many times a value is greater than the one right before it.
n = int(input())numbers = []for i in range(n): numbers.append(int(input()))
increasing_count = 0for i in range(1, n): if numbers[i] > numbers[i - 1]: increasing_count += 1
print(increasing_count)This reads all the numbers into a list first, then loops through it starting from index 1, comparing each number with the one before it. The counter and the condition are the same two pieces as before. Only the source of the items has changed, from input() calls to a list index.
Common mistakes
The two mistakes above, forgetting to initialize the counter and overwriting instead of accumulating, are the most common. A third is placing the += at the wrong indentation level. It belongs inside the if block, not at the end of the loop body. If count += 1 sits outside the if, aligned with the loop instead of the condition, it runs on every iteration rather than only when the condition is true. Check your indentation carefully when a count comes out too high.
Using a loop variable as a counter is the last trap. The loop variable i counts which iteration you are on (0, 1, 2, and so on). A counter variable tracks how many items match a condition, and the two are not interchangeable. If you only have i, you cannot tell at the end how many items matched, only how many you looked at.
Practice
Try these on the judges. Each link opens the problem on WMOJ or DMOJ.
- 2022 J2Fergusonball Ratings (opens on WMOJ in a new tab) WMOJ
Process two lines of data per player and flag those meeting a condition.
- 2020 J3Art (opens on DMOJ in a new tab) DMOJ
Scan a comma-separated line of numbers, tracking the minimum and maximum as you go.
Why DMOJ: A running-minimum-and-maximum scan, the same one-pass shape as this lesson's counters.
- 2019 J2Time to Decompress (opens on DMOJ in a new tab) DMOJ
Expand a run-length compressed string and process the result in a loop.
Why DMOJ: A one-pass scan with a running total, in the same style as this lesson's examples.