In this article we are going to see how we can count the digits of a number using recursion by Java programming language.
Java Program to Count the Digits of a Number Using Recursion
Let’s see the program.
- Java Program to Count the Digits of a Number Using Recursion By Using Static Input Value
- Java Program to Count the Digits of a Number Using Recursion By Using User Input Value
Method-1: Java Program to Count the Digits of a Number Using Recursion By Using Static Input Value
Approach:
- Create a static integer variable ‘
ctr
’ and store any number in it. - Call the user defined method
calcDigits( )
and store the result in an integer variable ‘digits
’ - So
calcDigits( )
is an user-defined method that increments the counter and calls the method by dividing the digits by 10. - Print the result.
Program:
import java.util.*; // Main class public class Main { // counter to store the count static int ctr=0; // Method to count the number of digits in a number using recursion public static int calcDigits(int num) { // Till number is greater than zero keep on incrementing the counter if(num!=0) { ctr++; // Divides the number by 10 and recursively calls the method calcDigits(num/10); } return ctr; } public static void main(String[] args) { int num = 3962; // Call the method and store the result int digits = calcDigits(num); // Print the result System.out.println("The number of digits in "+num+" is "+digits); } }
Output: The number of digits in 3962 is 4
Method-2: Java Program to Count the Digits of a Number Using Recursion By Using User Input Value
Approach:
- Create a static integer variable ‘
ctr
‘ - Ask the user to enter a number and store it in an integer variable ‘
num
‘ - Call the user defined method
calcDigits( )
and store the result in an integer variable ‘digits
’ - So
calcDigits( )
is an user-defined method that increments the counter and calls the method by dividing the digits by 10. - Print the result.
Program:
import java.util.*; // Main class public class Main { // counter to store the count static int ctr=0; // Method to count the number of digits in a number using recursion public static int calcDigits(int num) { // Till number is greater than zero keep on incrementing the counter if(num!=0) { ctr++; // Divides the number by 10 and recursively calls the method calcDigits(num/10); } return ctr; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number to calculate its digits - "); int num = sc.nextInt(); // Call the method and store the result int digits = calcDigits(num); // Print the result System.out.println("The number of digits in "+num+" is "+digits); } }
Output: Enter the number to calculate its digits - 965 The number of digits in 965 is 3
Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.