This blog is under construction

Wednesday 17 July 2013

C program to find the most and least frequent character in a string

Write a C program to find the most and least frequent character in a string.


  #include <stdio.h>
  #include <string.h>

  int main() {
        char data[256];
        int i = 0, small, big, characters[52] = {0};
        int index;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(data, 256, stdin);
        data[strlen(data) - 1] = '\0';

        /*
         * Occurance of uppercase characters are stored
         * in the index 0-25 of characters array.  Lower
         * case characters occurace are stored at the indices
         * 26 - 51
         */
        while (data[i] != '\0') {
                if (data[i] >= 'A' && data[i] <= 'Z') {
                        index = data[i] - 'A';
                        characters[index]++;
                }else if(data[i] >= 'a' && data[i] <= 'z') {
                        index = 26 + (data[i] - 'a');
                        characters[index]++;
                }
                i++;
        }

        big = characters[0];

        /* find the max occurance */
        for (i = 0; i < 52; i++) {
                if (big < characters[i]) {
                        big = characters[i];
                }
        }

        /* find the min occurance */
        small = big;
        for (i = 0; i < 52; i++) {
                if (small > characters[i] && characters[i] != 0) {
                        small = characters[i];
                }
        }

        /* print all characters with minimum(small) occurrence */
        printf("Least Frequent Characters:");
        for (i = 0; i < 52; i++) {
                if (characters[i] == small) {
                        if (i > 25) {
                                printf("%c", (i - 26) + 'a');
                        } else {
                                printf("%c", (i + 'A'));
                        }
                }
        }

        printf(" occured %d times\n", small);

        /* print all characters with maximum(big) occurrence */
        printf("Most Frequent Characters:");
        for (i = 0; i < 52; i++) {
                if (characters[i] == big) {
                        if (i > 25) {
                                printf("%c", (i - 26) + 'a');
                        } else {
                                printf("%c", (i + 'A'));
                        }
                }
        }
        printf(" occured %d times\n", big);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:helloworld
  Least Frequent Characters : dehrw occurred 1 times
  Most Frequent Characters:l occurred 3 times



No comments:

Post a Comment