Approach
- Find each digit of the number. We find digit by dividing number by 10 and getting remainder.
- Calculate sum by adding each obtained digit.
Method 1 – Iterative
import java.util.Scanner; public class DigitSum { public static void main(String[] args) { int input; Scanner scanner = new Scanner(System.in); System.out.print("Enter the number:"); input = scanner.nextInt(); int result = getSum(input); System.out.println("Sum of Digits:"+result); } static int getSum(int input){ int sum = 0; while (input != 0){ sum = sum + (input % 10); input = input/10; } return sum; } }
Method 2 – Single line
import java.util.Scanner; public class DigitSum { public static void main(String[] args) { int input; Scanner scanner = new Scanner(System.in); System.out.print("Enter the number:"); input = scanner.nextInt(); int result = getSum(input); System.out.println("Sum of Digits:"+result); } static int getSum(int input){ int sum; for (sum = 0; input > 0; sum += input % 10, input /= 10); return sum; } }
Method 3 – Recursive
import java.util.Scanner; public class DigitSum { public static void main(String[] args) { int input; Scanner scanner = new Scanner(System.in); System.out.print("Enter the number:"); input = scanner.nextInt(); int result = getSum(input); System.out.println("Sum of Digits:"+result); } static int getSum(int input) { return input == 0 ? 0 : input%10 + getSum(input/10) ; } }
Output
Enter the number:243
Sum of Digits:9