You are here

C program to count number of vowels in a string

C program to count number of vowels in a string: C programming code to find how many vowels are present in a string. For example, in the string "C programming" there are three vowels 'o', 'a' and 'i'. In the program both lower and upper case are considered i.e 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O' and 'U'. In our program we check every character in the input string, if it's a vowel then counter is incremented by one, consonants and special characters are ignored.

Count vowels in a string in C

#include <stdio.h>
 
int main()
{
  int c = 0, count = 0;
  char s[1000];
 
  printf("Input a string\n");
  gets(s);
 
  while (s[c] != '\0') {
    if (s[c] == 'a' || s[c] == 'A' || s[c] == 'e' || s[c] == 'E' || s[c] == 'i' || s[c] == 'I' || s[c] =='o' || s[c]=='O' || s[c] == 'u' || s[c] == 'U')
      count++;
    c++;
  }
 
  printf("Number of vowels in the entered string: %d", count);
 
  return 0;
}

Output of C program to count number of vowels in a string:
C program to count number of vowels in a string output

C program to count vowels in a string using function

#include<stdio.h>
 
int count_vowels(char []);
int check_vowel(char);
 
main()
{
   char array[100];
   int c;
 
   printf("Enter a string\n");
   gets(array);
 
   c = count_vowels(array);
 
   printf("Number of vowels: %d\n", c);
 
   return 0;
}
 
int count_vowels(char a[])
{
   int count = 0, c = 0, flag;
   char d;
 
   do
   {   
      d = a[c];
 
      flag = check_vowel(d);
 
      if ( flag == 1 )
         count++;
 
      c++;
   } while( d != '\0' );
 
   return count;
}
 
int check_vowel(char a)
{
   if ( a >= 'A' && a <= 'Z' )
      a = a + 'a' - 'A';   /* Converting to lower case */
 
   if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
      return 1;
 
   return 0;
}