I was trying to solve a question. I need to count which vowels appears most in a string. The input is given from user. I can count the vowels from the string but how can I count which vowel appears most of the time in the string.
Here's my code -
#include <stdio.h>
int main()
{
int vCount = 0; int vA = 0, vE = 0, vI = 0, vO = 0, vU = 0;
char str[100]; printf("Enter String: "); gets(str);
for(int i=0; i<strlen(str); i )
{
str[i] = tolower(str[i]);
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u')
{
vCount ;
}
if(str[i] == 'a')
{
vA ;
}
else if(str[i] == 'e')
{
vE ;
}
else if(str[i] == 'i')
{
vI ;
}
else if(str[i] == 'o')
{
vO ;
}
else if(str[i] == 'u')
{
vU ;
}
}
printf("\nNumber of vowels: %d\n", vCount);
return 0;
}
CodePudding user response:
You need to define a mapping between vowel and its occurrences. In the first step count how many times each vowel appears. After you have this info, just sort the values in descending order to show the most frequent ones first. Below code is in python but the idea can be translated in C:
text = input("Enter a text: ")
vowels_number = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
# Count vowels
for char in text:
if char.lower() in vowels_number:
vowels_number[char.lower()] = 1
# Sort vowels_number in descending order
print(f"Most frequent vowels: {sorted(vowels_number.items(), key=lambda item: item[1], reverse=True)}")
For input aaaaAaaeEiIoUu
, above code will output:
Most frequent vowels: [('a', 7), ('e', 2), ('i', 2), ('u', 2), ('o', 1)]