asked 28.8k views
1 vote
Write a method that returns the number of vowels in a string reclusively. You should call your method vowel count (a) Sample input 1 (apple). (b) Sample Output 1 (2). (c) Sample Input 2 (Computer science).

asked
User Moku
by
8.8k points

1 Answer

0 votes

Final answer:

To count the number of vowels in a string recursively, you can define a recursive function called vowelCount. The function should check if the first character is a vowel and increment a count variable accordingly. Here is an example implementation in Java.

Step-by-step explanation:

To write a method that returns the number of vowels in a string recursively, you can define a recursive function called vowelCount. The function should take a string as input and check if the first character is a vowel. If it is, increment a count variable by 1. Then, recursively call the vowelCount function with the remaining substring.

Here is an example implementation in Java:

public class VowelCounter {
public static int vowelCount(String str) {
if(str.length() == 0) {
return 0;
}
char firstChar = Character.toLowerCase(str.charAt(0));
int count = 0;
if(firstChar == 'a' || firstChar == 'e' || firstChar == 'i' || firstChar == 'o' || firstChar == 'u') {
count = 1;
}
return count + vowelCount(str.substring(1));
}

public static void main(String[] args) {
String input = "apple";
int vowelCount = vowelCount(input);
System.out.println("Number of vowels: " + vowelCount);
}
}

In this example, the input string is "apple" and the output will be 2, as there are two vowels ('a' and 'e') in the string.

answered
User Prince Sodhi
by
8.1k points