Program in C & C++ to count frequency of each letter in a string
C PROGRAM
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> void del(char *str,int *p) { int i; for(i=*p;i<strlen(str);i++) { if(str[i]==str[i+1]){ *p=*p-1; } else str[i]=str[i+1]; } } void frequency(const char *str1) { char letter[26],*str; int num[50],i,j,k; int len=strlen(str1); str=(char*)malloc(len+1); strcpy(str,str1); for(i=0;i<len;i++) { k=1; for(j=i+1;j<=len;j++) { if(tolower(str[i])==tolower(str[j])) { k=k+1; letter[i]=str[i]; num[i]=k; del(str,&j); } else { letter[i]=str[i]; num[i]=k; } } } printf("letter \t Frequency\n"); for(i=0;i<strlen(letter);i++) printf("%2c\t%6d\n",letter[i],num[i]); } int main() { frequency("Hello World"); return 0; }
C++ PROGRAM
#include<iostream> #include<conio.h> #include<string.h> #include<ctype.h> using namespace std; void del(char *str,int &p) { for(int i=p;i<strlen(str);i++) { if(str[i]==str[i+1]){ p=p-1; } else str[i]=str[i+1]; } } void frequency(const char *str1) { char letter[26],*str; int num[50],i,j,k; int len=strlen(str1); str=new char[len+1]; strcpy(str,str1); for(i=0;i<len;i++) { k=1; for(j=i+1;j<=len;j++) { if(tolower(str[i])==tolower(str[j])) { k=k+1; letter[i]=str[i]; num[i]=k; del(str,j); } else { letter[i]=str[i]; num[i]=k; } } } cout<<" "<<"letter"<<"\t "<<"Frequency"<<endl; for(i=0;i<strlen(letter);i++) cout<<" "<<letter[i]<<"\t "<<num[i]<<endl; } int main() { frequency("Programming.OM"); return 0; }
Output :-
Program
0 Comments