Java Sum of Digits Program

By | July 16, 2019

Task: Java Sum of Digits Program

Write a program in Java to find Sum of Digits of a given Number. For example, the sum of digits will be equal to 10 if we enter the number 730, since 7+3+0 = 10.

Source Code For Java Sum of Digits Program

/*
   Java Sum of Digits Program 
   Write a Java program to input a number
   and show the sum of digits of that number.
   Example:The sum of digits = 6 if given input
   number is 123, because of 1+2+3.
*/
package sumofdigits;
/**
 * @author www.EasyCodeBook.com
 */
import java.util.Scanner;
public class SumOfDigits {

    public static void main(String[] args) {
        int sum = 0, num, n, rem ;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number to find sum of its digits:");
        num = input.nextInt();
        n=num;
        while(n != 0)
        {
        rem = n%10;
        sum=sum+rem;
        n = n/10;
        }
        System.out.println("Sum of digits: " + sum);
    }
}
    

Output of Sum of Digits:

run:
Enter a number to find sum of its digits:256
Sum of digits: 13
BUILD SUCCESSFUL (total time: 5 seconds)

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *