Friday, 28 August 2015

Sum of digits of a number N using recursion in Java

Hello friends,

I am here with you with an easy problem.

Given a number N , we need to output the sum of the digits of the number N.

This can be solved using iteration but for learning purpose lets do it using recursion.

Friends, please find the code below for this problem.

package com.recursion.sumofdigits;

import java.util.Scanner;

public class SumOfDigitsOfNumN {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Number: ");
        int number = sc.nextInt();
        System.out.println("Sum of digits is "+getSum(number));
    }
    
    public static int getSum(int number){
        int lsd = number%10; // least significant digit
        int remainingNum = number/10;
        if(remainingNum == 0){
            return lsd;
        }
        return lsd+getSum(remainingNum);
    }
}