C program to find minimum occurring character in a string

Write a C program to find minimum occurring character in a string using loop. How to find lowest frequency character in a string using loop in C programming. Program to find minimum frequency character in a given string in C.

Example:
Input string: I love C programming!
Output lowest frequency: 'I' = 1

Required knowledge

Basic C programming, Loop, Array, String

Logic to find lowest frequency character in string

Logic to this program involves basic two steps:
  1. Find frequency of each character and store it in some integer array.
  2. Find the minimum element in the frequency array. The minimum value of the frequency array except 0 will be the minimum occurring character in given string.


Program to find lowest frequency character in string

/**
 * C program to find minimum occurring character in a string
 */

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the string
#define MAX_CHARS 255 //Maximum characters allowed


int main()
{
    char string[MAX_SIZE];
    int frequency[MAX_CHARS]; //Stores frequency of each character
    int i = 0, min;
    int ascii;

    printf("Enter any string: ");
    gets(string);

    /* Initializes frequency of all characters to 0 */
    for(i=0; i<MAX_CHARS; i++)
    {
        frequency[i] = 0;
    }


    /* Finds frequency of each characters */
    i=0;
    while(string[i] != '\0')
    {
        ascii = (int)string[i];
        frequency[ascii] += 1;

        i++;
    }


    /* Finds minimum frequency */
    min = 0;
    for(i=0; i<MAX_CHARS; i++)
    {
        if(frequency[i] != 0)
        {
            if(frequency[min] == 0 || frequency[i] < frequency[min])
                min = i;
        }
    }


    printf("Lowest frequency of '%c' is %d.\n", min, frequency[min]);

    return 0;
} 


Output
Enter any string: I love C programming!
Lowest frequency of '!' is 1.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment