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.
![[Solved] Sum of digits with Java [Solved] Sum of digits with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Sum-of-digits-with-Java.png)
![[Solved] Command Line Arguments II with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Command-Line-Arguments-II-with-Java-300x200.png)
![[Solved] Command Line Argument Print String with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Command-Line-Argument-Print-String-with-Java-300x200.png)
![[Solved] Reverse the digits with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Reverse-the-digits-with-Java-300x200.png)