C Source Code/Count the number of vowels in a word
Appearance
Introduction
[edit | edit source]Each time you see a vowel, add one. For example:
because.
b (no) e (+1=1) c (no) a (+1=2) u (+1=3) s (no) e (+1=4)
One way of doing this is to scan the string "because" from left to right. We read in a character, and check if it is a vowel. The character is compared to a dictionary of vowels. This "dictionary" is stored in the line
static const char vowels[] = "aeiouAEIOU";
so in this code, the lowercase and uppercase letters are all vowels.
The code
[edit | edit source]#include <stdio.h>
#include <string.h>
/* main: main loop for counting vowels in word */
int main(void)
{
size_t i, j, word_len, vowels_len;
int vowel_count;
char word[21]; /* 20 + '\0' */
static const char vowels[] = "aeiouAEIOU";
printf("Enter a word: ");
scanf("%20s", word);
/* initialise variables */
word_len = strlen(word);
vowels_len = strlen(vowels);
vowel_count = 0;
for (i = 0; i < word_len; ++i) { /* loop through word */
for (j = 0; j < vowels_len; ++j) { /* loop through vowels */
if (word[i] == vowels[j]) {
++vowel_count;
break;
}
}
}
printf("\nThe no. of vowels in '%s' is %d\n", word, vowel_count);
/* indicate success */
return 0;
}
Line by line explanation
[edit | edit source]- ...
- ...
- ...