Write a Java program to count total number of consonants using recursion


This program takes a string as input and counts the number of consonants in it. It uses a recursive approach to traverse the string and check if each character is a consonant or not.

The totalConsonants method takes two arguments: the input string str and its length n. It first checks if the length of the string is 1. If it is, it checks if the character is a consonant and returns 1 if it is and 0 if it isn't. If the length of the string is more than 1, it recursively calls itself with the string length reduced by 1. If the last character is a consonant, it adds 1 to the result of the recursive call, otherwise, it returns the result of the recursive call without adding anything.

The isConsonant method takes a character as input and returns true if it is a consonant and false otherwise. It first converts the character to uppercase and then checks if it is not a vowel (A, E, I, O, U) and lies in the range of uppercase letters (ASCII value 65 to 90).

Overall, this program is a good example of how recursion can be used to solve a simple problem like counting the number of consonants in a string.

Source Code

import java.util.*;
import java.lang.*;
class Total_Consonants
{
	public static void main(String args[])
	{
		String str = "Tutor Joes";
		System.out.println("Given String : "+str);
		System.out.println("Number of Consonants : "+totalConsonants(str, str.length()));
	}
	static int totalConsonants(String str, int n)
	{
		if (n == 1)
		{
			if(isConsonant(str.charAt(0)))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
 
		if(isConsonant(str.charAt(n - 1)))
		{
			return totalConsonants(str, n - 1) + 1;
		}
		else
		{
			return totalConsonants(str, n - 1);
		}
	}
	static boolean isConsonant(char ch)
	{
		ch = Character.toUpperCase(ch);
 
		return (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')== false && ch >= 65 && ch <= 90;
	}
}

Output

Given String : Tutor Joes
Number of Consonants : 5