Popular Posts

July 16, 2024

Sum of Each Digit In The Given Number Using Recursion Java Program

 

Sum of Each Digit In The Given Number Using Recursion Java Program

Program:

Write a program to find sum of each digit in the given number using recursion?

Description:

Below example shows how to find out sum of each digit in the given number using
recursion logic. For example, if the number is 259, then the sum should be 2+5+9 = 16.

Code:

package com.java2novice.algos;

public class MyNumberSumRec {

    int sum = 0;
    
    public int getNumberSum(int number){
        
        if(number == 0){
            return sum;
        } else {
            sum += (number%10);
            getNumberSum(number/10);
        }
        return sum;
    }
    
    public static void main(String a[]){
        MyNumberSumRec mns = new MyNumberSumRec();
        System.out.println("Sum is: "+mns.getNumberSum(223));
    }
}

Output:

Sum is: 7

Here's a Java program that calculates the sum of each digit in a given number using recursion:

import java.util.Scanner;

public class DigitSumRecursion {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        
        int sum = sumOfDigits(number);
        
        System.out.println("The sum of the digits is: " + sum);
        
        scanner.close();
    }

    public static int sumOfDigits(int number) {
        // Base case: if the number is 0, the sum is 0
        if (number == 0) {
            return 0;
        }
        // Recursive case: sum the last digit and the sum of the remaining digits
        return (number % 10) + sumOfDigits(number / 10);
    }
}

Explanation:

  1. Input: The program prompts the user to enter an integer.
  2. Recursion:
    • The sumOfDigits method checks if the number is 0. If it is, it returns 0 (base case).
    • Otherwise, it calculates the last digit (number % 10) and adds it to the result of a recursive call with the number divided by 10 (removing the last digit).
  3. Output: The program prints the total sum of the digits.

Example:

  • For input 1234, the output will be The sum of the digits is: 10 because 1+2+3+4=101 + 2 + 3 + 4 = 10.

No comments:
Write comments