Introduction:
In programming, a frequency counter is a tool used to count how many times each element or character appears in a given input, such as a string or array. In this case, we’ll be focusing on counting the frequency of each character in a string. This is useful in various applications such as text analysis, pattern recognition, and compression algorithms.
Objective:
The goal of this program is to write a C++ application that takes an input string and counts how many times each character appears in the string. By the end of the program, the user will see a frequency distribution of the characters in the input string.
Program Code in C++
#include #include #include using namespace std; int main() { string inputString; cout << "Enter a string: "; getline(cin, inputString); // Taking input string // Create an unordered map to store character frequencies unordered_map<char, int> freqCounter; // Loop through each character of the string for (char c : inputString) { freqCounter[c]++; // Increment the frequency count for each character } // Display the frequency of each character cout << "Character frequencies in the string are:" << endl; for (const auto& pair : freqCounter) { cout << pair.first << ": " << pair.second << endl; } return 0; }
Explanation of the Program Structure:
The program starts by including the necessary libraries:
- iostream – for input/output operations.
- unordered_map – to store the characters and their frequencies efficiently.
- string – for handling the input string.
The main program performs the following steps:
- It prompts the user to enter a string.
- The input string is stored in the variable
inputString
. - An
unordered_map
calledfreqCounter
is created to hold the frequency of each character. - We loop through each character in the string. For each character, we increment its count in the
freqCounter
. - After processing the string, we print the frequency of each character stored in the map.
How to Run the Program:
To run this C++ program, follow these steps:
- Open your preferred C++ development environment (IDE) or a text editor.
- Copy and paste the provided code into a new C++ file (for example, frequency_counter.cpp).
- Compile the program using a C++ compiler. For example, if you’re using the command line, run:
g++ frequency_counter.cpp -o frequency_counter
. - Run the compiled program by typing
./frequency_counter
(on Linux or macOS) orfrequency_counter.exe
(on Windows). - Enter a string when prompted and the program will display the frequency of each character in the string.