Question 6
Back to Exercise
Count the vowels and consonants in a sentence by walking through it with a char pointer.
Solution
#include <stdio.h>
#include <ctype.h>
int main(void) {
const char *s = "Pointers make C powerful";
int vowels = 0, consonants = 0;
for (const char *p = s; *p; p++) {
char c = (char) tolower((unsigned char) *p);
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d\nConsonants: %d\n", vowels, consonants);
return 0;
}
Vowels: 8 Consonants: 13
The loop runs until *p is the terminating zero. tolower() handles capital letters, and only letters are counted, so spaces are skipped.
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!