Frequency
Language: C
To write a program in C that counts the frequency of characters in a given string, you can follow these steps:
- Declare an array of size 256 to store the frequency of each character. Initialize all elements of the array to 0.
- Read the input string from the user.
- Iterate over each character in the input string.
- For each character, increment the corresponding element in the frequency array.
- Print the frequency of each character.
Here's an example implementation:
#include <stdio.h>
int main() {
char input[100];
int frequency[256] = {0};
int i;
printf("Enter a string: ");
scanf("%[^\n]", input);
for (i = 0; input[i] != '\0'; i++) {
frequency[(int)input[i]]++;
}
printf("Character frequencies:\n");
for (i = 0; i < 256; i++) {
if (frequency[i] > 0) {
printf("%c: %d\n", (char)i, frequency[i]);
}
}
return 0;
}
Explanation of the steps:
- We declare an array
frequency
of size 256 to store the frequency of each character. Since there are 256 possible ASCII characters, this array can store the frequency of any character. - We declare a character array
input
to store the user's input string. The size of the array is set to 100, but you can adjust it according to your needs. - We use
scanf
with the%[^\n]
format specifier to read the input string from the user. This format specifier reads characters until a newline character is encountered. - We initialize all elements of the
frequency
array to 0 using the{0}
initializer. - We iterate over each character in the
input
string using afor
loop. The loop continues until the null character ('\0'
) is encountered, indicating the end of the string. - For each character, we increment the corresponding element in the
frequency
array. We cast the character to an integer using(int)
to get its ASCII value, which serves as the index in thefrequency
array. - Finally, we print the frequency of each character by iterating over the
frequency
array. We only print characters that have a frequency greater than 0.
I hope this helps! Let me know if you have any further questions.