Java program to find sum of digits

By | 2018-03-21T22:12:01+05:30 June 25th, 2016|java programs|

In this Java programming tutorials, I am going to show you how to calculate sum of digits till we get the single digit in java.

Input : Give any integer like : 658456

Output : 7

Sum of digits Example :

package com.onlinetutorialspoint.javaprograms;
import java.util.Scanner;
public class SumOfNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long number, sum = 0, rem;
        System.out.print("Enter any number:");
        number = sc.nextLong();
        while (number >= 10) {
            sum = 0;
            while (number != 0) {
                rem = number % 10;
                number = number / 10;
                sum += rem;
            }
            if (sum >= 10) {
                number = sum;
            } else {
                break;
            }
        }
        System.out.println("Sum of Digits : " + sum);
    }
}

Output :

Enter a number:-658456
Sum of Digits : 7

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment