In this example, we will calculate the sum of the Digits of a Number in java taking the value from the user. Before we begin, you should have knowledge on the following topic in Java:
Explanation: This is an easy program if you have the working technique of the operator. Suppose the entered number is 123, we will create a program in a loop that will add these three digits such as 1 + 2 + 3. And display the result.
Java Program to Find a Factorial of a Number Using for loop
//calculate the sum of the digits of a number in java
import java.util.Scanner;
public class SumOfDigits
{
public static void main(String args[])
{
int num, temp, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number: ");
num = s.nextInt();
while(num > 0)
{
temp = num % 10;
sum = sum + temp;
num = num / 10;
}
System.out.println("Sum of the entered Digits:"+sum);
}
}
Output:
Enter the number: 4567
Sum of the entered Digits:22