Sum of Digits of a Number in Java
Steps to Find the Sum of Digits of a Number in Java
Enter any integer number as input. After that, we use modulus and division operation respectively to find the sum of digits of the number as output. Let's see the steps.
Let's understand the above steps mathematically and find the sum of digits of a number.
Suppose, we have to find the sum of digits of the number (N) 674.
674 % 10 = 4
Sum = 0 + 4 = 4
674 / 10 = 67
67 % 10 = 7
Sum = 4 + 7 = 11
67 / 10 = 6
6 % 10 = 6
Sum = 11 + 6 = 17
6 / 10 = 0
Now the number (N) has become 0. So, we will not process it further. Hence, we get 17 as the sum of digits of the number 674.
Let's implement the above steps in a Java program.
Java Programs to Find the Sum of Digits of a Number
There are the following ways to find the sum of digits of a number:
Using While Loop
Enter the number: 876 Sum of Digits: 21
Using for Loop
Enter a number: 3456788 Sum of digits: 41
The sum of digits: 26
In the following program, we have reduced the lines of code and implement the steps in a for loop only.
The sum of digits: 35
The sum of digits: 28
Let's create another Java program for the same.
Enter a number: 983451 The sum of digits: 30