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:

  1. Include Header Files: #include <stdio.h> is used to include the standard input/output functions in the program.

  2. Main Function: int main() is the main function where the program execution begins.

  3. Variables:

  4. char str[100]: Declares a character array str to store input string with a maximum size of 100 characters.
  5. int i: Integer variable used as a loop counter.
  6. int freq[256] = {0}: Array freq initialized to store the frequency of each character in the ASCII range (0-255). Each element represents the count of a specific character.

  7. User Input: printf("Enter a string: "); prompts the user to input a string.

  8. fgets(str, sizeof(str), stdin);: Reads the string input from the user using fgets() and stores it in the str array.

  9. Calculate Frequency:

  10. for (i = 0; str[i] != '\0'; i++): Loop through each character of the input string until the null character ('\0') is encountered.
  11. freq[(int)str[i]]++;: Increments the frequency count of the character at str[i] index in the freq array.

  12. Display Frequency:

  13. printf("Frequency of each character in the string:\n");: Prints the header for the frequency output.
  14. for (i = 0; i < 256; i++): Iterates through each possible ASCII character.

    • if (freq[i] != 0): Checks if the frequency of character i is not zero.
      • printf("'%c' occurs %d times\n", i, freq[i]);: Prints the character (i) and its frequency stored in freq[i].
  15. Return Statement: return 0; signifies the end of the main() function and returns an exit status of 0 to the operating system.