📖 Scenario: You are working in a small grocery store. You want to count how many times each fruit appears in a list of fruits sold today.
🎯 Goal: Build a program that counts the frequency of each fruit sold using a hash map (dictionary) and prints the counts.
📋 What You'll Learn
Create an array of fruits with exact values
Create a hash map (dictionary) to store fruit counts
Use a loop to count the frequency of each fruit
Print the frequency of each fruit in the format: fruit: count
💡 Why This Matters
🌍 Real World
Counting frequencies is useful in stores to track sales, in text analysis to count words, and in many other data processing tasks.
💼 Career
Understanding frequency counting with hash maps is a key skill for software developers, data analysts, and anyone working with data structures.
Progress0 / 4 steps
1
Create the list of fruits sold
Create a char* array called fruits with these exact values: "apple", "banana", "apple", "orange", "banana", "apple".
DSA C
Hint
Use an array of char* strings and count the number of fruits in a separate variable.
2
Set up the hash map for counting
Create a struct called FruitCount with two fields: char* fruit and int count. Then create an array called counts of size 3 to store FruitCount elements. Initialize all count fields to 0.
DSA C
Hint
Use a struct to hold fruit name and count. Initialize counts for each fruit to zero.
3
Count the frequency of each fruit
Write a for loop with variable i from 0 to fruits_count - 1. Inside it, write another for loop with variable j from 0 to 2 to compare fruits[i] with counts[j].fruit using strcmp. If they match, increase counts[j].count by 1.
DSA C
Hint
Use nested loops and strcmp to compare strings and update counts.
4
Print the frequency of each fruit
Write a for loop with variable k from 0 to 2. Inside the loop, print the fruit and its count in the format: fruit: count using printf.
DSA C
Hint
Use a loop and printf to display each fruit and its count on a new line.
Practice
(1/5)
1. What is the main purpose of using a hash map in the Frequency Counter Pattern?
easy
A. To reverse the order of elements in the collection
B. To sort the elements in ascending order
C. To remove duplicate elements from the collection
D. To count how many times each element appears in a collection
Solution
Step 1: Understand the role of a hash map
A hash map stores key-value pairs, allowing quick lookup and update of counts.
Step 2: Apply to frequency counting
Using a hash map, we can track how many times each element appears by incrementing counts.
Final Answer:
To count how many times each element appears in a collection -> Option D