Count the Alphabet

From CompSciWiki
Revision as of 03:16, 6 December 2011 by RalviV (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Loop through the alphabet and count how many consonants and vowels there are. Print a statement with the counts. Your ouput should look something like this:

 There are 5 vowels in the English alphabet.
There are 21 consonants in the English alphabet. 

Hint: 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

Wiki loops03.jpg

Solution

The 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; 


Starting at 0 ('a'), loop through the alphabet until you've looped 26 times (the number of letters in the alphabet, NUMLETTERS). If any vowels are found, increase the vowel count. Move to the next letter by increasing the letter count.

 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."); 


Here is the complete solution.

Code

Solution Code

Back to the Program-A-Day homepage