count number of vowels in a string in c
To count the number of vowels in a string in C, you can use the following code:
#include <stdio.h>
int countVowels(char *str) {
int count = 0;
while (*str) {
if (str == 'a' || str == 'e' || str == 'i' || str == 'o' || *str == 'u' ||
str == 'A' || str == 'E' || str == 'I' || str == 'O' || *str == 'U') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int vowels = countVowels(str);
printf("Number of vowels in the string: %d\n", vowels);
return 0;
}
This code defines a function countVowels
that takes a string as input and counts the number of vowels in it. The function uses a while loop to iterate over each character in the string. If the character is a vowel (either lowercase or uppercase), the count is incremented. The function then returns the final count.
In the main
function, the user is prompted to enter a string. The fgets
function is used to read the string from the user. The countVowels
function is called with the input string, and the resulting count is printed to the console.
Note that this code assumes the input string is null-terminated and has a maximum length of 100 characters.