Java program to find the sum of digits of a number using recursion

Given a number, we have to find the sum of digits using the recursion.
Submitted by Nidhi, on June 02, 2022

Problem Solution:

In this program, we will read an integer number from the user and then we will calculate the sum of the digits of the input number using recursion.

Program/Source Code:

The source code to find the sum of digits of a number using recursion is given below. The given program is compiled and executed successfully.

// Java program to find the sum of digits of a number 
// using the recursion

import java.util.*;

public class Main {
  static int sum = 0;

  public static int sumOfDigits(int num) {
    if (num > 0) {
      sum += (num % 10);
      sumOfDigits(num / 10);
    }

    return sum;
  }

  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 = sumOfDigits(num);
    System.out.printf("Sum of digits is: " + res);
  }
}

Output:

Enter number: 3452
Sum of digits is: 14

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 sumOfDigits(), main(). The sumOfDigits() is a recursive method that calculates the sum of 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 sumOfDigits() method to calculate the sum of digits of the input number and printed the result.

Java Recursion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.