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(;
        // put your code here
        int num = scanner.nextInt();
        int ans = 0;
        while (num > 0) {
            ans += num % 10;
            num /= 10;

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.


Popular Posts from this Blog

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

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala