Skip to content

Instantly share code, notes, and snippets.

@aadipoddar
Created April 7, 2022 14:01
Show Gist options
  • Save aadipoddar/c1f5da10f72f19057e5b2e1c4b90e3b2 to your computer and use it in GitHub Desktop.
Save aadipoddar/c1f5da10f72f19057e5b2e1c4b90e3b2 to your computer and use it in GitHub Desktop.
Count Vowels Using Recursion
/*
Write a program to accept a word using String accept() function
and count the number of vowels in the word using int vowels(String, int) recursive function
and display the word and the frequency of vowels in the word using void display(String, int) function.
*/
import java.util.Scanner;
class VowelsRecursion {
String accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
return in.nextLine();
}
int vowels(String word, int length) {
if (length == 0)
return 0;
else {
if (word.charAt(length) == 'a' || word.charAt(length) == 'e' || word.charAt(length) == 'i'
|| word.charAt(length) == 'o' || word.charAt(length) == 'u')
return 1 + vowels(word, length - 1);
else
return vowels(word, length - 1);
}
}
void display(String word, int count) {
System.out.println("Word: " + word);
System.out.println("Number of vowels: " + count);
}
public static void main(String[] args) {
VowelsRecursion obj = new VowelsRecursion();
String sen = obj.accept();
obj.display(sen, obj.vowels(sen.toLowerCase(), sen.length() - 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment