frequency
#include <stdio.h>
int main() {
char str[100];
int i, freq[256] = {0};
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
}
printf("Frequency of each character in the string:\n");
for (i = 0; i < 256; i++) {
if (freq[i] != 0) {
printf("'%c' occurs %d times\n", i, freq[i]);
}
}
return 0;
}
Explanation:
Include Header Files:
#include <stdio.h>
is used to include the standard input/output functions in the program.Main Function:
int main()
is the main function where the program execution begins.Variables:
char str[100]
: Declares a character arraystr
to store input string with a maximum size of 100 characters.int i
: Integer variable used as a loop counter.int freq[256] = {0}
: Arrayfreq
initialized to store the frequency of each character in the ASCII range (0-255). Each element represents the count of a specific character.User Input:
printf("Enter a string: ");
prompts the user to input a string.fgets(str, sizeof(str), stdin);
: Reads the string input from the user usingfgets()
and stores it in thestr
array.Calculate Frequency:
for (i = 0; str[i] != '\0'; i++)
: Loop through each character of the input string until the null character ('\0'
) is encountered.freq[(int)str[i]]++;
: Increments the frequency count of the character atstr[i]
index in thefreq
array.Display Frequency:
printf("Frequency of each character in the string:\n");
: Prints the header for the frequency output.for (i = 0; i < 256; i++)
: Iterates through each possible ASCII character.if (freq[i] != 0)
: Checks if the frequency of characteri
is not zero.printf("'%c' occurs %d times\n", i, freq[i]);
: Prints the character (i
) and its frequency stored infreq[i]
.
Return Statement:
return 0;
signifies the end of themain()
function and returns an exit status of 0 to the operating system.