Question

Java programming Write a method that recursively calculates the sum of digits for an integer. 121...

Java programming

Write a method that recursively calculates the sum of digits for an integer.

121 would be 1 + 2 + 1 which is 4.

Hint: %10 would give you the final digit.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;

public class SumOfDigits {

    public static int sumOfDigits(int n) {
        if (n < 0)
            return sumOfDigits(-1 * n);
        else if (n == 0)
            return 0;
        else
            return (n % 10) + sumOfDigits(n / 10);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = in.nextInt();
        System.out.println("Sum of digits of " + n + " is " + sumOfDigits(n));
    }
}

Add a comment
Know the answer?
Add Answer to:
Java programming Write a method that recursively calculates the sum of digits for an integer. 121...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT