Slip No 16 Q A

Q.Write a java program to calculate sum of digits of a given number using recursion.[15 M]

import java.util.Scanner;

public class SumOfDigits {

    // Recursive method to calculate sum of digits
    public static int sumDigits(int n) {
        // Base case
        if (n == 0)
            return 0;
        else
            return (n % 10) + sumDigits(n / 10);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = sc.nextInt();

        // Handle negative numbers
        number = Math.abs(number);

        int result = sumDigits(number);

        System.out.println("Sum of digits: " + result);

        sc.close();
    }
}

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top