Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot