Home »
Java »
Java Programs
Java program to count the digits of a number using recursion
Given a number, we have to count the total number of digits of the given number using the recursion function.
Submitted by Nidhi, on June 01, 2022
Problem statement
In this program, we will read an integer number from the user, and then we will count the digits of the input number using recursion.
Java program to count the digits of a number using recursion
The source code to count the digits of a number using recursion is given below. The given program is compiled and executed successfully.
// Java program to count the digits of a number
// using the recursion
import java.util.*;
public class Main {
static int count = 0;
public static int countDigits(int num) {
if (num > 0) {
count++;
countDigits(num / 10);
}
return count;
}
public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int num = 0;
int res = 0;
System.out.printf("Enter number: ");
num = X.nextInt();
res = countDigits(num);
System.out.printf("Total digits are: " + res);
}
}
Output
Enter number: 5869456
Total digits are: 7
Explanation
In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods countDigits(), main(). The countDigits() is a recursive method that counts the digits of the specified number and returns the result to the calling method.
The main() method is the entry point for the program. Here, we read an integer number from the user and called the countDigits() method to count the digits of the input number and printed the result.
Java Recursion Programs »