You are here

C program to count number of vowels in a string

C program to count number of vowels in a string: for example, in the string "love" there are two vowels 'o' and 'e'. In the program both lower and upper case are considered i.e., 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u' and 'U'. In this 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

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int c = 0, count = 0;
  6.   char s[1000];
  7.  
  8.   printf("Input a string\n");
  9.   gets(s);
  10.  
  11.   while (s[c] != '\0') {
  12.     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')
  13.       count++;
  14.     c++;
  15.   }
  16.  
  17.   printf("Number of vowels in the string: %d", count);
  18.  
  19.   return 0;
  20. }

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

  1. #include<stdio.h>
  2.  
  3. int count_vowels(char []);
  4. int check_vowel(char);
  5.  
  6. int main()
  7. {
  8.    char array[100];
  9.    int c;
  10.    
  11.    printf("Enter a string\n");
  12.    gets(array);
  13.    
  14.    c = count_vowels(array);
  15.    
  16.    printf("Number of vowels: %d\n", c);
  17.    
  18.    return 0;
  19. }
  20.  
  21. int count_vowels(char a[])
  22. {
  23.    int count = 0, c = 0, flag;
  24.    char d;
  25.    
  26.    do
  27.    {  
  28.       d = a[c];
  29.      
  30.       flag = check_vowel(d);
  31.      
  32.       if (flag == 1)
  33.          count++;
  34.      
  35.       c++;
  36.    } while (d != '\0');
  37.    
  38.    return count;
  39. }
  40.  
  41. int check_vowel(char ch)
  42. {
  43.    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
  44.       return 1;
  45.  
  46.    if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
  47.       return 1;
  48.    
  49.    return 0;
  50. }