Skip to content
Related Articles

Related Articles

C program to count number of vowels and consonants in a String

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Sep, 2022
Improve Article
Save Article

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




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

Output:

String: geeks for geeks
Vowels: 5
Consonants: 8

Time Complexity: O(1)

Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!