How to Sum the Digits of a Given Number in Java


In this example, we will learn how to find sum of each digit in the given number in Java.

Source Code

package com.beginner.examples;

public class DigitSumExample {
     
    public static void main(String[] args){
    	int sum = 0, a;
        int number = 437;
        while (number > 0) {
        	//Redundancy on module 10
            a = number % 10;
            number = number / 10;
            sum += a;
        }
        System.out.println("Sum is: " + sum);
      }
}

Output:

Sum is: 14
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments