Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive method digitSum that takes a non-negative integer in return fo

ID: 3808504 • Letter: W

Question

Write a recursive method digitSum that takes a non-negative integer in return for some of its digits. For example, digitSum(1234) returns 1 + 2 + 3 + 4 = 10. Your method should take advantage of the fact that it is easy to break a number into two smaller pieces by dividing by 10 (i.e, 1234/10 = 123 and 1234%10 = 4). For these methods, we do not need to construct any objects. Therefore, you can declare them to be static methods and call them directly from main: public static int digitSum(int n) {ellipsis}

Explanation / Answer

DigitSum.java
public class DigitSum {
public static int digitSum(int n) {
if ( n <= 9) return n;
else
{
return (n%10) + digitSum(n/10);
}
}
  
public static void main(String[] args) {
System.out.println("Sum of digits of 1234 is: " + digitSum(1234));
}
}

Sample output

Sum of digits of 1234 is: 10

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote