Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Easy
  • Last Updated : 25 Nov, 2019

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;
}
Output:
String: geeks for geeks
Vowels: 5
Consonants: 8

Attention reader! Don’t stop learning now. Join the First-Step-to-DSA Course for Class 9 to 12 students , specifically designed to introduce data structures and algorithms to the class 9 to 12 students




My Personal Notes arrow_drop_up
Recommended Articles
Page :