Pin It

Write a Java program to calculate sum of the digits of a number entered by the user.

Program to calculate sum of the digits of a number entered by the user in Java

package com.hubberspot.java.example;

import java.util.Scanner;

public class SumOfDigitsDemo {

    public static void main(String[] args) {

        Integer number;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number whose" +
                " sum of digits is to be calculated : ");

        number = scanner.nextInt();

        System.out.println("Number entered : " + number);

        int sum = 0;

        while(number > 0) { 
            int digit = number % 10;
            sum = sum + digit;
            number = number / 10;
        }

        System.out.println("The sum of the digits of the" +
                " number entered : " + sum);        
    }
}



Output of the program : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot