Java Program to find the sum of digits of a number using recursion


In this program, you will learn how to find the sum of digits of a number using recursion in java.


4321 => 4 + 3 + 2 + 1

1232 => 1 + 2 + 3 + 2

Example: How to find the sum of digits of a number using recursion in java.

import java.util.Scanner;

class Main {
    int s = 0, r;

    int sumOfDigits(int n) {

        if (n > 0) {
            r = n % 10;
            s = s + r;
            sumOfDigits(n / 10);
        }

        return s;
    }

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

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

        Main obj = new Main();
        int sum = obj.sumOfDigits(n);

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

    }
}

Output:

Enter a number:4326
Sum of digits:15

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.