Java Program to find Sum of digits of a Number - The Coding Shala

Home >> Java Programs >> Sum of digits of a number

In this post, we will learn how to write a Java program to find the sum of digits of a given number.

Sum of Digits of a Number Java Program

We will take a reminder of 10 that will give us the last digits of the given number. Add this digit to sum and divide the number by 10 and repeat this step until input number is greater than 0.

Example 1:
Input: 476
Output: 17
Explanation: 4 + 7 + 6  = 17.

Java Program: 

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // put your code here
        int num = scanner.nextInt();
        int ans = 0;
        while (num > 0) {
            ans += num % 10;
            num /= 10;
        }
        System.out.println(ans);
    }
}

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala