Back to the Program-A-Day homepage
Problem
Loop 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
|
Solution
|
Code
Solution Code
public class CountTheAlphabet
{
public static void main(String[] args)
{
//final indicates that this is a constant
//Uppercase also indicates that this is a constant
final int NUMLETTERS = 26;
//the initial value of letter will be a since we are printing out the lower case alphabet.
char letter = 'a';
int vowels = 0;
int consonants = 0;
//our for loop will run from 0 to NUMLETTERS - 1
for(int i = 0; i < NUMLETTERS; i++)
{
if(letter=='a' || letter=='e' || letter=='i' || letter=='o'
|| letter=='u')
{
//increases the vowel count by 1
vowels++;
letter++;
}
//increases the consonant count by 1
else
{
consonants++;
letter++;
}
}
System.out.println("There are " + vowels + " vowels in the English alphabet.");
System.out.println("There are " + consonants + " consonants in the English alphabet.");
}
}
|
Back to the Program-A-Day homepage