[Solved] Sum of digits with Java

Write a program to find the sum of digits in a number using recursion.

Input and Output Format:

Input consists of a nonnegative integer.

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.

 

Sample Input and Output:

Enter the value of n

432

The sum of digits in 432 is 9

Solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n, a;
        System.out.println("Enter the value of n");
        n = s.nextInt();
        a = sum(n);
        System.out.println("The sum of digits in " + n + " is " + a);
    }

    public static int sum(int n) {
        if (n == 0)
            return 0;
        return (n % 10 + sum(n / 10));
    }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

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