Menu
Coddy logo textTech

Recap - Word Frequency

Part of the Logic & Flow section of Coddy's C++ journey — lesson 29 of 56.

challenge icon

Challenge

Easy

Create a program that counts word frequencies in a text passage using a std::map. Your program will track how many times each unique word appears and then report the frequency of a specific word.

The following inputs will be provided:

  • An integer n representing the number of words in the text
  • Then n strings representing the words in the text
  • A string representing the target word to check frequency for

Your program should:

  1. Create a std::map<std::string, int> named wordCount
  2. Read the number of words
  3. For each word, read it and update its count in the map using the square bracket operator and increment
  4. Read the target word to check
  5. Print the frequency of the target word using the format shown below

Use the following exact output format:

The word "[target_word]" appears [frequency] times

If the target word doesn't exist in the map, accessing it with the square bracket operator will automatically create an entry with a count of 0, so you can safely print the frequency without checking if the word exists first. Use wordCount[word]++ to increment the count for each word as you read it - this will create new entries with count 1 for new words, or increment existing counts for words already seen.

Try it yourself

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // Read the number of words
    int n;
    cin >> n;
    
    // Create the map to store word frequencies
    map<string, int> wordCount;
    
    // TODO: Write your code here
    // Read n words and update their counts in the map
    // Then read the target word and output its frequency
    
    return 0;
}

All lessons in Logic & Flow