- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print characters and their frequencies in order of occurrence in C++
This problem, We are given a string of lowercase characters. and we have to find the frequencies of each character that occurs in the string. the below example when explaining more about the problem.
Input : “jskdk” Output : j 1 s 1 k 2 d 1
Explanation − In the String, the characters j, s, d occur once and k occurs twice. Hence, the output printed gives the above result.
Now let's create a logic to solve this problem. As stated we have to find the frequency of occurrence of each character in the string. One logical way is to traverse the string and count the frequency of occurrence of a character and store it in an array and then print the character along with their frequency of occurrence.
Algorithm
Step 1 : Create an array of size 26 that stores the frequency of characters in the string. Step 2 : print all the characters along with their frequency of occurrence from the array.
Example
Now, let’s create a program to find the solution to this problem,
#include <bits/stdc++.h> using namespace std; int main(){ string str = "tutorialspoint"; int n = str.size(); int frequency[26]; memset(frequency, 0, sizeof(frequency)); for (int i = 0; i < n; i++) frequency[str[i] - 'a']++; for (int i = 0; i < n; i++) { if (frequency[str[i] - 'a'] != 0) { cout<<str[i]<<"\t"<<frequency[str[i] - 'a']<<"\n"; frequency[str[i] - 'a'] = 0; } } return 0; }
Output
t 3 u 1 o 2 r 1 i 2 a 1 l 1 s 1 p 1 n 1
- Related Articles
- Print characters having odd frequencies in order of occurrence in C++
- Print numbers in descending order along with their frequencies
- Print 2-D co-ordinate points in ascending order followed by their frequencies in C++
- Print the last occurrence of elements in array in relative order in C Program.
- Print common characters of two Strings in alphabetical order in C++
- Print all distinct characters of a string in order in C++
- Queries for frequencies of characters in substrings in C++
- XOR of Prime Frequencies of Characters in a String in C++
- Python code to print common characters of two Strings in alphabetical order
- Java code to print common characters of two Strings in alphabetical order
- Print n smallest elements from given array in their original order
- Print all permutations with repetition of characters in C++
- C program to print characters and strings in different formats.
- Print * in place of characters for reading passwords in C
- Print all prime factors and their powers in C++

Advertisements