Frequency

Language: C

To write a program in C that counts the frequency of characters in a given string, you can follow these steps:

  1. Declare an array of size 256 to store the frequency of each character. Initialize all elements of the array to 0.
  2. Read the input string from the user.
  3. Iterate over each character in the input string.
  4. For each character, increment the corresponding element in the frequency array.
  5. 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:

  1. 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.
  2. 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.
  3. 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.
  4. We initialize all elements of the frequency array to 0 using the {0} initializer.
  5. We iterate over each character in the input string using a for loop. The loop continues until the null character ('\0') is encountered, indicating the end of the string.
  6. 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 the frequency array.
  7. 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.