Home Tutorial Java Core Java Sum of Digits

 
 

Java Sum of Digits
Posted on: November 10, 2009 at 12:00 AM
In this section, you will learn how to find the sum of multidigit number in Java.

Java Sum of Digits

In this Java Tutorial section, you will learn how to find the sum of multidigit number. For this purpose, we have allowed the user to enter multidigit number. User can enter any digit number but cannot exceed to 9 digit. Following code calculates the sum of digits:

while (n > 0) {
			int p = n % 10;
			sum = sum + p;
			n = n / 10;
		}

Here is the code for Sum of Digits in Java:

import java.util.*;

class SumOfDigits {
	public static void main(String args[]) {
		int sum = 0;
		System.out.println("Enter multi digit number:");
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int t = n;
		while (n > 0) {
			int p = n % 10;
			sum = sum + p;
			n = n / 10;
		}
		System.out.println("sum of the digits in " + t + " is " + sum);
	}
}

Output

Enter multi digit number:
123456789
sum of digits in 123456789 is 45

Related Tags for Java Sum of Digits:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.