Counting Matching Elements
Counting matching elements in an array means looking at each item one by one and keeping a running tally of how many times a specific target value appears. Imagine you are a teacher checking how many students scored exactly 50 marks in a math test by going down the roll list and dropping a pebble in
The ideaLink to this section
Counting matching elements in an array means looking at each item one by one and keeping a running tally of how many times a specific target value appears. Imagine you are a teacher checking how many students scored exactly 50 marks in a math test by going down the roll list and dropping a pebble in a jar each time you see a 50. In Java, we loop through the array, check each element against our condition using an if statement, and add 1 to a counter variable whenever it matches. By the end of the loop, our counter holds the exact frequency of the target value. This is a foundational array technique used everywhere from simple data filtering to basic statistics.
note
Worked example: Counting Winning ScoresLink to this section
A cricket coach wants to know how many players in a team scored exactly 50 runs in the recent tournament. Given an array of runs scored by each player, count how many players scored 50.
Input format
- Line 1: an integer N, the number of players
- Line 2: N space-separated integers, the runs scored by each player
Output format
- Line 1: a single integer representing the count of players who scored 50
How it worksLink to this section
- Read N = 5 and create an array of size 5.
- Read the 5 run values: 25, 50, 75, 50, and 10 into the array.
- Initialize the counter variable to 0.
- Loop through the array: index 0 is 25 (no match), index 1 is 50 (count becomes 1), index 2 is 75 (no match), index 3 is 50 (count becomes 2), index 4 is 10 (no match).
- Print the final count of 2.
note
warning
Quick checkLink to this section
What is the primary purpose of a counter variable when traversing an array?
Practice 1: Count Defective Bulbs (Medium)Link to this section
tip
Practice 2: Passing Students Count (Hard)Link to this section
tip
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion