54.7k views
5 votes
Description FULL JAVA CODE PLEASE Write a recursive method (no loops) which takes in a non-negative integer and returns the sum of all the digits in a number. You should call this method recursive Sum. For Example: recursive Sum(126) would return 9 as 1+2+6=9 Input n, where n is a non-negative integer Sample Input 126 Output The sum of all single digits in a number Sample Output Result =9

1 Answer

2 votes

Final answer:

To calculate the sum of the digits in a number recursively in Java, you can define a method called recursiveSum. This method takes an integer as input and returns the sum of its digits. The code uses recursion to extract each digit and make a recursive call to compute the sum.

Step-by-step explanation:

To calculate the sum of the digits in a number recursively in Java, you can start by defining a recursive method called recursiveSum. This method takes an integer as input and returns an integer as output. Inside the method, you can check the base case where the input number is less than 10. In this case, you simply return the input number as the sum of its digits.

If the input number is greater than 10, you can extract the last digit using the modulus operator (%). Then, you can make a recursive call to the same method with the remaining digits of the number (obtained by integer division by 10) and add the extracted digit to the result. Finally, you return the sum computed by the recursive call.

Here's the full Java code for the recursiveSum method:

public class RecursiveSum {
public static int recursiveSum(int n) {
if (n < 10) {
return n;
}
return n % 10 + recursiveSum(n / 10);
}
}

User Sony Packman
by
8.3k points