This is a C++ Program to Print Each Letter in a String followed by its Frequency.
The program takes a string and prints the frequency of each letter in the string.
1. The program takes a string.
2. The number of times a letter occurs in the string is recorded.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Print Each Letter in a String followed by its Frequency. The program output is shown below.
#include<iostream>
#include <string.h>
using namespace std;
int main ()
{
char str[50];
int i, len, freq[26];
cout << "Enter a string : ";
gets(str);
len = strlen(str);
for(i = 0; i < 26; i++)
freq[i] = 0;
for(i = 0; i < len; i++)
{
if(str[i] >= 'a' && str[i] <= 'z')
freq[str[i] - 97]++;
else if(str[i] >= 'A' && str[i] <= 'Z')
freq[str[i] - 65]++;
}
cout << "Frequency of characters\n";
for(i = 0; i < 26; i++)
{
if(freq[i] != 0)
{
cout << " " << static_cast<char>(i + 'a') << " : " << freq[i];
cout << "\n";
}
}
return 0;
}
1. The program takes a string and stores in the array ‘str’. The length of str is stored in the variable ‘len’.
2. Another array ‘freq’ of size 26 is initialized as 0 to store frequencies of all the letters.
3. Using a for loop, every character in the string is counted and incremented in its corresponding array.
4. The loop terminates when the string ends.
5. The list of letters and their frequencies are printed if frequency is not 0.
Case 1 : Enter a string : Ball Frequency of characters a : 1 b : 1 l : 2 Case 2 : Enter a string : ababababab Frequency of characters a : 5 b : 5 Case 3 : Enter a string : Hello World! Frequency of characters d : 1 e : 1 h : 1 l : 3 o : 2 r : 1 w : 1
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Apply for C++ Internship
- Check Programming Books
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Practice Programming MCQs