Tuesday 24 June 2014

C++ programs based on frequency of characters in a string

Here are C++ programs based on frequency of characters in a string. First program find frequency of characters using for-loop, second program find frequency of characters using recursion and third program print least and most frequent characters. 


C++ program to count the frequency of characters in a string
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    char str[100];
    int n=1;
    cout<<"Enter string : ";
    cin>>str;
    for(int i=0;str[i]!='\0';i++)
    {
        for(int y=i+1;str[y]!='\0';y++)
            if(str[i]==str[y]||str[i]==char(str[y]+32)||str[i]==char(str[y]-32))
            {
                str[y]=' ';
                n++;
            }
        if(str[i]>=65&&str[i]<=122)
           cout<<"Frequency of "<<str[i]<<" is : "<<n<<endl;
        n=1;
    }
    return 0;
}

OUTPUT




C++ program to find the frequency of characters in a string using recursion
#include<iostream>
#include<string.h>
using namespace std;
int frstr(char ch,char (&str)[50],int i,int freq)
{
    if(str[i]=='\0')
        return freq;
    else
    {
        if(ch==str[i])
        {
           freq++;
           str[i]=' ';
        }
        return frstr(ch,str,i+1,freq);
    }
}
int main()
{
    char str[50];
    int lenght;
    cout<<"Enter string : ";
    cin>>str;
    for(int i=0;str[i]!='\0';i++)
        if(str[i]!=' ')
           cout<<"Frequency of "<<str[i]<<" is "<<frstr(str[i],str,i+1,1)<<endl;
    return 0;
}

OUTPUT




C++ program to find the most and least frequent character in a string
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    char str[100],smchtr[10],lrchtr[10];
    int smfre=30,lrfre=0,n=1,k=0,l=0;
    cout<<"Enter string : ";
    cin>>str;
    for(int i=0;str[i]!='\0';i++)
    {
        for(int y=i+1;str[y]!='\0';y++)
            if(str[i]==str[y]||str[i]==char(str[y]+32)||str[i]==char(str[y]-32))
            {
                str[y]=' ';
                n++;
            }
        if(str[i]>=65&&str[i]<=122)
        {
            if(smfre>n)
            {
              smchtr[0]=str[i];
              smfre=n;
              k=0;
            }
            else if(smfre==n)
                smchtr[++k]=str[i];
            if(lrfre<n)
            {
                lrchtr[0]=str[i];
                lrfre=n;
                l=0;
            }
            else if(lrfre==n)
                lrchtr[++l]=str[i];
        }
        n=1;
    }
    cout<<"Most frequent characters with frequency "<<lrfre<<" : ";
    for(int i=0;i<=l;i++)
       cout<<lrchtr[i]<<" ";
    cout<<"\nLeast frequent characters with frequency "<<smfre<<" : ";
    for(int i=0;i<=k;i++)
       cout<<smchtr[i]<<" ";
    return 0;
}

OUTPUT




No comments:

Post a Comment