We are assuming that you will not enter a sentence longer than 255 characters, so we have defined our string variable accordingly. When prompted, enter a sentence that will be assigned to the str variable. Because a sentence may have blank spaces between the words, we will execute the gets function to accept the sentence.
The two variables that we've defined, that is, ctrV and ctrC, are initialized to 0. Because the last character in a string is always a null character, \0, a while loop is executed, which will access each character of the sentence one by one until the null character in the sentence is reached.
Every accessed letter from the sentence is checked to confirm that it is either an uppercase or lowercase character. That is, their ASCII values are compared, and if the ASCII value of the accessed character is a lowercase or uppercase character, only then it will execute the nested if block. Otherwise, the next character from the sentence will be accessed.
Once you have ensured that the accessed character is not a blank space, any special character or symbol, or a numerical value, then an if block will be executed, which checks whether the accessed character is a lowercase or uppercase vowel. If the accessed character is a vowel, then the value of the ctrV variable is incremented by 1. If the accessed character is not a vowel, then it is confirmed that it is a consonant, and so the value of the ctrC variable is incremented by 1.
Once all of the characters of the sentence have been accessed, that is, when the null character of the sentence is reached, the while loop terminates and the number of vowels and consonants stored in the ctrV and ctrC variables is displayed on the screen.
Let's use GCC to compile the countvowelsandcons.c program, as follows:
D:\CBook>gcc countvowelsandcons.c -o countvowelsandcons
Let's run the generated executable file, countvowelsandcons.exe, to see the output of the program:
D:\CBook>./countvowelsandcons
Enter a sentence: Today it might rain. Its a hot weather. I do like rain
Number of vowels are : 18
Number of consonants are : 23
Voilà! We've successfully counted all of the vowels and consonants in our sentence.
Now, let's move on to the next recipe!