0
0
DSA C++programming~30 mins

Count Occurrences of Element in Sorted Array in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Count Occurrences of Element in Sorted Array
📖 Scenario: You have a sorted list of product IDs representing items sold in a store. You want to find out how many times a specific product ID appears in this list.
🎯 Goal: Build a program that counts how many times a given product ID appears in a sorted array of product IDs.
📋 What You'll Learn
Create an array called product_ids with the exact values: {101, 102, 102, 102, 103, 104, 104, 105}
Create an integer variable called target_id and set it to 102
Write a function called countOccurrences that takes the array product_ids, its size, and target_id as parameters and returns the count of target_id in the array
Print the count returned by countOccurrences
💡 Why This Matters
🌍 Real World
Counting how many times a product appears in sales data helps stores understand product popularity and manage inventory.
💼 Career
This skill is useful for software developers working with data analysis, inventory management systems, and any application needing frequency counts in sorted data.
Progress0 / 4 steps
1
Create the sorted array of product IDs
Create an integer array called product_ids with these exact values: {101, 102, 102, 102, 103, 104, 104, 105}
DSA C++
Hint

Use C++ array syntax to create product_ids with the given values.

2
Set the target product ID to count
Create an integer variable called target_id and set it to 102
DSA C++
Hint

Declare target_id as an integer and assign it the value 102.

3
Write the function to count occurrences
Write a function called countOccurrences that takes three parameters: an integer array called arr, an integer size, and an integer target. The function should return the number of times target appears in arr. Use a for loop with variable i to iterate from 0 to size - 1 and count matches.
DSA C++
Hint

Use a loop to check each element and increase count when you find target.

4
Print the count of the target product ID
Print the result of calling countOccurrences with product_ids, the size of product_ids (which is 8), and target_id. Use std::cout to display the count.
DSA C++
Hint

Use std::cout to print the count returned by countOccurrences.