Home Tutorial Java Core Java Sum of Digits

 
 

Share on Google+Share on Google+
Java Sum of Digits
Posted on: November 10, 2009 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java Sum of Digits:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 10, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com