C Program: Count the Number of Vowels in a String
In this tutorial, we will write a C program to find/count the number of vowels in a given string.
The vowels, a
, e
, i
, o
, u
, could either be in lowercase or uppercase; the program will find/count them both.
Here is the program. Inside the while
loop, the if
condition checks for both lowercase and uppercase vowels. If the condition is met, the vowels
variable is incremented. Also, the printf()
statement prints the vowel inside the condition.
#include <stdio.h>
int main() {
unsigned short count = 0, vowels = 0;
char str[100], c;
printf("Enter a string: ");
scanf("%[^\n]", str);
while(str[count] != '\0') {
c = str[count];
if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I'
|| c == 'o' || c == 'O' || c == 'u' || c == 'U') {
vowels++;
printf("%c", c);
}
count++;
}
printf("\n");
printf("NUMBER OF VOWELS: %hu \n", vowels);
return 0;
}
On running the program, the prompt to enter a string will appear. Enter some string.
$ ./a.out
Enter a string: POWERFUL YOU HAVE BECOME
The output of the above string - POWERFUL YOU HAVE BECOME
- is as follows: