- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C program to find the frequency of a character in a string
In this article, you will learn and get code for finding the frequency of a character in a given string. That is, how many times a specific character appears in a given string. For example, if the user enters the string as "fresherearth," and wants to check for the frequency of a character, say "c," then it will be 3. Because c occurs 3 times in the given string "fresherearth."
The question is, "Write a program in C to find the frequency of any given character in a given string." Both strings and characters will be entered by the user (at run-time). The answer to this question is:
#include<stdio.h> #include<conio.h> int main() { int i, count=0; char str[100], ch; printf("Enter the String: "); gets(str); printf("Enter any character (present in string) to find its frequency: "); scanf("%c", &ch); for(i=0; str[i]!='\0'; i++) { if(ch==str[i]) count++; } printf("\nFrequency of %c = %d", ch, count); printf("\n\n%c occurs %d times in %s", ch, count, str); getch(); return 0; }
As the above program is written in the Code::Blocks IDE, therefore, after a successful build and run, here is its sample run:
Now enter any string, say "fresherearth," and press the ENTER key. Then enter any character that presents itself inside the string "fresherearth", say "c", and press the ENTER again to see the frequency of "c" in "fresherearth."
Program Explained
- Get string input from the user using the gets() function.
- Get character input from the user using the scanf() function.
- We've now created a for loop to check each and every character of the string, from the 0th to the null terminated character ('\0') of the string.
- Whenever the character matches with the character at any place in the string, then increment the count variable's value.
- Because the count variable was initially set to 0, it now holds the total number of times the character appears within the string.
- For example, let's suppose the string is "fresherearth" (in the str variable) and the character is "c" (in the ch variable).
- As a result, str[0] contains c, str[1] contains o, str[2] contains d, str[3] contains e,... str[9] contains k, str[10] contains e, and str[11] contains r.
- The character c is presented at index numbers 0, 5, and 8. total of three times.
- Therefore, the count variable gets incremented three times. Because the condition ch==str[i] is met three times, because ch holds c and str[0], str[5], and str[8] also hold c.
- Therefore, the frequency of c in the given string, say "fresherearth," will be 3.
Find the frequency of each character in a string
Now let's modify the above program and, instead of finding the frequency of one particular character, let's find the frequency of every character present in the given string:
#include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[100], ch; int i, j, k, len, count=0; printf("Enter the string: "); gets(str); len = strlen(str); printf("\n"); for(i=0; i<len; i++) { ch = str[i]; for(j=0; j<len; j++) { if(ch==str[j]) { count++; for(k=j; k<(len-1); k++) { str[k] = str[k+1]; } len--; str[len] = '\0'; j--; } } printf("%c = %d times\n", ch, count); count=0; i--; } getch(); return 0; }
Here is the sample run:
Now supply any string, say "we love fresherearth," and press ENTER to see the frequency of all the characters one by one as shown in the screenshot given below:
Program Explained
- We've used one outer loop to run until the string contains a null-terminated character ('\0').
- And in the inner loop, we have used the same loop with another variable.
- Before the inner loop, we've initialized the initial character of the string to the ch variable.
- And then comes the inner loop.
- In this loop, we checked to see if the value of ch is present anywhere in the string; if it is, we incremented the count variable and then shifted one index back all the characters of the string, so str[1] is shifted to str[0], str[2] is shifted to str[1], and so on.
- As the character is counted up, therefore, the character at that particular place has no further use, so we have shifted and deleted that character from the string using the second inner for loop using another variable.
- After exiting the loop, decrement the string length, say len, and append a null-terminated character ('\0') to the string's last index.
- And then decrement the second inner for loop variable and continue to run until the condition of the first inner for loop evaluates to be false.
- After this, print the output and initialize the count to 0 and decrement the value of the outer loop.
- In this way, the frequency of all the characters is calculated and printed one by one.
Print the frequency of each character along with the remaining characters
Here is another program that lists out all the characters' frequencies along with the remaining characters in the string:
#include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[100], ch; int i, j, k, len, count=0; printf("Enter the string: "); gets(str); len = strlen(str); printf("\n"); printf("Character\tCount\t\tString Left\n\n"); for(i=0; i<len; i++) { ch = str[i]; for(j=0; j<len; j++) { if(ch==str[j]) { count++; for(k=j; k<(len-1); k++) str[k] = str[k+1]; len--; str[len] = '\0'; j--; } } printf("%c occurs \t%d times\t\t%s\n", ch, count, str); count=0; i--; } getch(); return 0; }
Here is its sample run:
Now supply any string, say "fresherearth," and press enter to check it out:
The same program in different languages
- C++ Find Frequency of Character in String
- Java Find Frequency of Character in String
- Python Find Frequency of Character in String
« Previous Program Next Program »