Java Program to Count the Frequency of Each Vowel in a Given String

Write a program to count the frequency of each vowel in a given string in Java.

For example,

Input
"My name is John Smith"
Output
Number of 'a' = 1 
Number of 'e' = 1  
Number of 'i' = 2 
Number of 'o' = 1 
Number of 'u' = 0

Steps

  1. Let str be the input string.
  2. Initialize an integer array of size 5. Let the name of the array be cnt.
  3. Fill cnt with zeros.
  4. cnt[0] stores the frequency of ‘a’, cnt[1] stores the frequency of ‘e’ and so on ( in order a,e,i,o,u ).
  5. Traverse each character of str using a loop
    1. If the character is ‘a’, increment cnt[0].
    2. If the character is ‘e’, increment cnt[1].
    3. If the character is ‘i’, increment cnt[2].
    4. If the character is ‘o’, increment cnt[3].
    5. If the character is ‘u’, increment cnt[4].
  6. Print the frequency of each vowel.
import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		String str;
		// array is always initialized with zeros
		int cnt[] = new int[5];

		System.out.print("Enter String: ");
		// reading input string
		str = sc.nextLine();

		for (int i = 0; i < str.length(); ++i) {
			if (str.charAt(i) == 'a' || str.charAt(i) == 'A') {
				cnt[0]++;
			}
			if (str.charAt(i) == 'e' || str.charAt(i) == 'E') {
				cnt[1]++;
			}
			if (str.charAt(i) == 'i' || str.charAt(i) == 'I') {
				cnt[2]++;
			}
			if (str.charAt(i) == 'o' || str.charAt(i) == 'O') {
				cnt[3]++;
			}
			if (str.charAt(i) == 'u' || str.charAt(i) == 'U') {
				cnt[4]++;
			}
		}

		System.out.println("Number of 'a' = " + cnt[0]);
		System.out.println("Number of 'e' = " + cnt[1]);
		System.out.println("Number of 'i' = " + cnt[2]);
		System.out.println("Number of 'o' = " + cnt[3]);
		System.out.println("Number of 'u' = " + cnt[4]);
	}
}

Output

Enter String: Hello, My name is Peter Pan 
Number of 'a' = 2
Number of 'e' = 4 
Number of 'i' = 1 
Number of 'o' = 1 
Number of 'u' = 0

Read

Leave a Comment

Your email address will not be published. Required fields are marked *