Java program to count vowels in a string (Iterative and Recursive)

Given a string, check the all out number of vowels (a, e, I, o, u) in it. There are two strategies to include all out number of vowels in a string.

1. Iterative 
2. Recursive

Examples: 

Input : abc de
Output : 2

Input : geeksforgeeks portal
Output : 7

1. Iterative Method 


Below is the implementation: 
 

// Java program to count vowels in a string
public class GFG {
		
	// Function to check the Vowel
	static boolean isVowel(char ch)
	{
		ch = Character.toUpperCase(ch);
		return (ch=='A' || ch=='E' || ch=='I' ||
						ch=='O' || ch=='U');
	}
	
	// Returns count of vowels in str
	static int countVowels(String str)
	{
		int count = 0;
		for (int i = 0; i < str.length(); i++)
			if (isVowel(str.charAt(i))) // Check for vowel
				++count;
		return count;
	}
	
	// Driver code
	public static void main(String args[])
	{
		//string object
		String str = "abc de";
	
		// Total numbers of Vowel
		System.out.println(countVowels(str));
	}
}
// This code is contributed by Sumit Ghosh

Output: 

2

 

Submit Your Programming Assignment Details