Site icon

Find sum of all digits of given number/Integer (java /example)

Problem Statement ?

Examples:

Program: calculate Sum of all digits of integer in java

package org.learn;

import java.util.Scanner;

public class SumOfDigits {

    private static int sum(int number) {

        int sumOfAllDigits = 0;
        while(number > 0) {
            sumOfAllDigits = sumOfAllDigits + number % 10;
            number = number / 10;
        }
        return sumOfAllDigits;
    }

    public static void main(String[] args) {

        try(Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter the input number: ");
            int input  = scanner.nextInt();
            System.out.println("Sum of all digits is : "+ sum(input));
        }
    }
}

Output: sum of all digits of integer/number in Java

Enter the input number: 299
Sum of all digits is : 20
Exit mobile version