Counting how often each character pops up in a string is a typical task in programming. So, you’ve got the string "hello world" and want to find out how frequently each character shows up. That’s what this program does! It’s pretty simple, but you’ll pick up quite a bit about arrays and string handling in C as you go.
We’ll use a frequency array to track each character's count. With this array, we can easily find out how many times a character appears in the string.
Prerequisites for the Frequency Program in C
You'll need to be familiar with these concepts to understand the program.
- Character arrays and the char data type
- Understanding of
forloops - Basic input and output in C
- Any C compiler such as GCC 9 or newer — or just run it in the EduSeekho online compiler
Source Code of C Program to Find the Frequency of Characters in a String
Here's the complete code for counting character frequency in a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int freq[256] = {0};
int i;
printf("Enter a string: ");
fgets(str, 100, stdin);
int len = strlen(str);
for (i = 0; i < len; i++) {
freq[(int)str[i]]++;
}
printf("Character frequencies:\n");
for (i = 0; i < 256; i++) {
if (freq[i] != 0) {
printf("%c: %d\n", i, freq[i]);
}
}
return 0;
}Try this code yourself — free
Run it in the EduSeekho online compiler. No setup needed.
Output of the Find Frequency Program
After running the program, you will see the following output for the input "hello world".
Enter a string: hello world
Character frequencies:
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
Algorithm to Find Frequency of Characters in C
Here's how the program works. It processes each character in the input string, updating the character's frequency count in an array. This array efficiently maps each character to its count.
- Read the input string from the user.
- Initialize a frequency array of size 256 to zero.
- Calculate the length of the string.
- Loop through each character in the string.
- Increment the frequency of the character in the array.
- After processing, loop through the frequency array.
- Print characters that have a non-zero frequency.
flowchart TD
A([Start]) --> B[/Enter a string/]
B --> C[Initialize frequency array to 0]
C --> D[Calculate length of string]
D --> E{Is string[i] != 0?}
E -->|Yes| F[frequency[string[i]]++]
F --> G[i++]
G --> E
E -->|No| H[Display frequencies of characters]
H --> I([End])How the C Program to Find Frequency Works
This section explains each part of the code in detail.
#include <stdio.h>and#include <string.h>: Include necessary headers for input/output and string handling.char str[100]: Declares a character array to store the string.int freq[256] = {0}: Initializes an array to count character frequencies, with 256 positions for each ASCII character.fgets(str, 100, stdin): Reads a line of text from the standard input.- The
forloop: Iterates over the string, updating the frequency count for each character. - The second
forloop: Checks the frequency array and prints characters with non-zero frequency. return 0: Ends the program successfully.
Quick Quiz — test your understanding
Tap an option to check your answerWhat is the purpose of the frequency array in this program?
Time and Space Complexity of the C Program to Find Frequency
This program efficiently calculates the frequency of characters using an array.
Time complexity: O(n). Here, n is the number of characters in the string, like 11 for "hello world". The for loop for (i = 0; i < len; i++) runs once per character. So, 10 characters mean 10 steps, 100 mean 100.
Space complexity: O(1). The program uses a fixed freq array of size 256 and a few integer variables (i, len) regardless of the string length.
Common mistake:Not initializing the frequency array to zero can mess up the counts.
Key takeaway:A frequency array helps you efficiently track character occurrences in a string.
FAQs About C Program to Find the Frequency of Characters
Here are some common questions about counting character frequencies in C.
if (str[i] == ' ') continue;fgets is safer for strings since it reads spaces and limits input size, which helps prevent buffer overflow.Related Programs
If you found this program helpful, check out these related programs:
- C Program to Sort Elements in Lexicographical Order
- C Program to Count Vowels and Consonants in a String
- C Program to Remove all Characters Except Alphabets
- C Program to Check Whether a Character is a Vowel or Consonant
- C Program to Check Whether a Character is an Alphabet
Conclusion
This program's a great example of using arrays to handle character data. Knowing how character frequencies work can come in handy for text analysis, encryption, and data compression. Try tweaking this code to manage different character sets or ignore specific characters. You can practice counting characters with the EduSeekho C quiz.
Check out the C programming quiz, or run this code in the EduSeekho online compiler.