C program to count number of vowels and consonants in a String
Given a string and write a C program to count the number of vowels and consonants in this string.
Examples:
Input: str = "geeks for geeks" Output: Vowels: 5 Consonants: 8 Input: str = "abcdefghijklmnopqrstuvwxyz" Output: Vowels: 5 Consonants: 21
Approach:
- Take the string as input
- Take each character from this string to check
- If this character is a vowel, increment the count of vowels
- Else increment the count of consonants.
- Print the total count of vowels and consonants in the end.
Below is the implementation of the above approach:
// C program to count the number of // vowels and consonants in a string #include <stdio.h> // Function to count number // of vowels and consonant void count_vowels_and_consonant( char * str) { // Declare the variable vowels and consonant int vowels = 0, consonants = 0; int i; char ch; // Take each character from this string to check for (i = 0; str[i] != '\0' ; i++) { ch = str[i]; // If this character is a vowel, // increment the count of vowels if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ) vowels++; // If this character is a space // skip it else if (ch == ' ' ) continue ; else // Else increment the count of consonants consonants++; } // Print the total count of vowels and consonants printf ( "\nVowels: %d" , vowels); printf ( "\nConsonants: %d" , consonants); } // Driver function. int main() { char * str = "geeks for geeks" ; printf ( "String: %s" , str); count_vowels_and_consonant(str); return 0; } |
chevron_right
filter_none
Output:
String: geeks for geeks Vowels: 5 Consonants: 8
Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.