Friday, 3 November 2023

Write a java program to calculate sum of digits of a given number using recursion. -Core java slip 16

Write a java program to calculate sum of digits of a given number using recursion.



import java.io.*;

 

public class SumOfDigits {

    public static void main(String[] args) {

        int number = 123;  // Change this to the number you want to calculate the sum for

        int sum = calculateSumOfDigits(number);

        System.out.println("The sum of digits in " + number + " is: " + sum);

    }

 

    public static int calculateSumOfDigits(int num) {

        if (num == 0) {

            return 0;  // Base case: If the number is 0, the sum is 0

        } else {

            // Calculate the sum of digits for the remaining part of the number

            int lastDigit = num % 10; // Get the last digit

            int remainingNumber = num / 10; // Remove the last digit

            return lastDigit + calculateSumOfDigits(remainingNumber); // Recursive call

        }

    }

}