Difference between revisions of "Count the Alphabet"
Line 48: | Line 48: | ||
There are 21 consonants in the English alphabet. | There are 21 consonants in the English alphabet. | ||
</pre> | </pre> | ||
− | + | ||
+ | Here is the complete solution. | ||
+ | |SolutionCode= | ||
<pre> | <pre> | ||
public class CountTheAlphabet | public class CountTheAlphabet |
Revision as of 11:02, 8 April 2010
Back to the Program-A-Day homepage
ProblemLoop through the alphabet to count how many consonants and vowels there are. Print a separate statement for each count. Remember: A char acts much the same way as an int does. You can perform arithmetic with char just like you can with an int. |
While and For Loops | |
---|---|---|
SolutionThe solution to this problem is similar to the "Print the Alphabet" problem in this chapter. In order to solve this problem, we use counters for the vowels and consonants and check the character after each iteration with an if-else statement. Here, we say that if any vowels are found, increase the vowel count by one. Otherwise, increase the consonant count. letter is the starting point for the counting in the alphabet. vowels and consonants are the counters. final int NUMLETTERS = 26; char letter = 'a'; int vowels = 0; int consonants = 0;
for(int i = 0; i < NUMLETTERS; i++) { if(letter=='a' || letter=='e' || letter=='i' || letter=='o' || letter=='u') If the char is not a vowel, then increase the consonant count and move to the next letter. else { consonants++; letter++; } Print your count statements. System.out.println("There are " + vowels + " vowels in the English alphabet."); System.out.println("There are " + consonants + " consonants in the English alphabet."); Your ouput should look something like this: There are 5 vowels in the English alphabet. There are 21 consonants in the English alphabet. Here is the complete solution. | ||
Code |