Write a Java program to count the digits of a number using recursion


The Java program counts the number of digits in an integer input by the user using a recursive function totalDigits().

The program prompts the user to enter an integer input, and then calls the totalDigits() function to count the number of digits in the input integer. The totalDigits() function uses recursion to count the digits in the input integer. If the input integer is greater than 0, the function increments a global variable tot by 1 and calls itself with the input integer divided by 10, until the input integer becomes 0. Finally, the function returns the value of the global variable tot, which contains the total number of digits in the input integer.

The program then outputs the total number of digits in the input integer using the System.out.print() function.

Source Code

import java.util.*;
public class CountDigits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int dig, tot ;
		System.out.print("Enter the Digits : ");
		dig = input.nextInt();
		tot = totalDigits(dig);
		System.out.print("Number of Digits : " + tot);
	}
	static int tot = 0;
	public static int totalDigits(int dig)
	{
		if (dig > 0)
		{
			tot++;
			totalDigits(dig / 10);
		}
		return tot;
	}
}

Output

Enter the Digits : 536412
Number of Digits : 6