In this section, you will learn how to find the sum of multidigit number in Java.
In this section, you will learn how to find the sum of multidigit number in Java.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