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
Geek Week

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! All those who say programming isn’t for kids, just haven’t met the right mentors yet. Join the  Demo Class for First Step to Coding Coursespecifically designed for students of class 8 to 12. 

The students will get to learn more about the world of programming in these free classes which will definitely help them in making a wise career choice in the future.




My Personal Notes arrow_drop_up
Recommended Articles
Page :