Frequency of a given character in a sentence – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#3243 siteicon   siteicon   siteicon  

Problem Statement - Frequency of a given character in a sentence

Write a program to input a small sentence from the user and ask about frequency of which character is to be found. Print how many times the character occurred in the given string. Do it for a a c-style (null-terminated string). Please note that the character frequency is to be found  irrespective of its lower or upper case.

Solution

TC++ #3243

#include 
#include
#include
int main()
{
clrscr();
char str[80];
cout<<"Input a small sentence:" ;
cin.getline(str,80);
char c;
cout<<"Input the character to be found:" ;
cin>>c;
int cc=0;
for(int i=0;str[i]!='';i++)
if(toupper(str[i])==toupper(c)) cc++;
cout<<"Frequency of given character = "
< getch();
return 0;
}
#include 
#include
using namespace std;
int main()
{
char str[80];
cout<<"Input a small sentence:" ;
cin.getline(str,80);
char c;
cout<<"Input the character to be found:" ;
cin>>c;
int cc=0;
for(int i=0;str[i]!='';i++)
if(toupper(str[i])==toupper(c)) cc++;
cout<<"Frequency of given character = "
< return 0;
}

Test it !
  Related (?) :

Run Output

Input a small sentence:Sports help to live a stress-free life.
Input the character to be found:s
Frequency of given character = 5

char str[80]; cout<<“Input a small sentence:” ; cin.getline(str,80);
A sentence is collected using the getline function of cin object.

char c; cout<<“Input the character to be found:” ; cin>>c;
A single character is collected usin cin.

int cc=0;  //This integer is used for character counting

for(int i=0;str[i]!=’’;i++)  if(toupper(str[i])==toupper(c)) cc++;
Here we traverse all the characters of the sentence till null termination is found. While in loop we compare upper converted character to upper converted character given by the user and if matched we increase the cout. This way we are able to ignore the case.

cout<<“Frequency of given character = ” <<cc<<endl;
The given character cout or in other terms called frequency is printed.

 

Notes

  • If space is given as character here, it can not be found as cin doesn’t allow to move further.
  • If more than 1 character is given then first of the given set of characters is found.
  • For ignoring case, both character in the sentence and character to be matched can be converted to lower case as well.
  • tolower() or toupper() functions do not effect numbers or symbols, so they can also be matched in this program.

Common Errors

  • Student often forget to initialise the counting variable.


Share

sunmitra| Created: 2-Feb-2018 | Updated: 2-Feb-2018|






Back