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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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


Output:

String: geeks for geeks
Vowels: 5
Consonants: 8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.