Question 2
Back to Exercise
Count the vowels in a word using one combined condition (no switch).
Solution
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *word = "Education";
int vowels = 0;
for (const char *p = word; *p; p++) {
int c = tolower((unsigned char) *p);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowels++;
}
printf("%s has %d vowels\n", word, vowels);
return 0;
}
Education has 5 vowels
Lower-casing first halves the number of tests. The || chain stops at the first match, so common vowels are found quickly.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!