adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C and C++ to count frequency of each character in a string

Program in C and C++ to count frequency of each character in a string

C Program
#include<stdio.h>
 void frequency(char *str){
    int i, count[26] = {0};
    char letters[26] = {0};
    i = 0;
    while((str[i] = tolower(str[i])) != '\0'){
        count[ str[i] - 'a' ]++;
        letters[str[i] - 'a' ] = str[i];
        i++;
    }
    for(i = 0; i < 26; i++)
        if(count[i] != 0)
          printf("%c - %d\n",letters[i],count[i]);
 }
 int main(){
    char *str = malloc(100);
    printf("Enter string :- ");
    gets(str);
    frequency(str);
    return 0;
 }
C++ Program
    #include<iostream>
 using namespace std;
 void frequency(char *str){
    int i, count[26] = {0};
    char letters[26] = {0};
    i = 0;
    while((str[i] = tolower(str[i]))!= '\0'){
        count[ str[i] - 'a' ]++;
        letters[str[i] - 'a' ] = str[i];
        i++;
    }
    for(i = 0; i < 26; i++)
        if(count[i] != 0)
          cout<<letters[i]<<"  "<<count[i]<<endl;
 }
 int main(){
    char *str = new char[100];
    cout<<"Enter string :- ";
    cin.getline(str,99);
    frequency(str);
    return 0;
 }
Output :-






Related Programs

Post a Comment

0 Comments