Javatpoint Logo
Javatpoint Logo

Sum of Digits of a Number in Java

In this section, we will create Java programs to find the sum of digits of a number in Java. In order to find the sum of digits of a number, we must familiar with the Java loops and operators.

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.

  1. Read or initialize an integer N.
  2. Declare a variable (sum) to store the sum of numbers and initialize it to 0.
  3. Find the remainder by using the modulo (%) operator. It gives the last digit of the number (N).
  4. Add the last digit to the variable sum.
  5. Divide the number (N) by 10. It removes the last digit of the number.
  6. Repeat the above steps (3 to 5) until the number (N) becomes 0.

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.

First iteration

674 % 10 = 4

Sum = 0 + 4 = 4

674 / 10 = 67

Second iteration

67 % 10 = 7

Sum = 4 + 7 = 11

67 / 10 = 6

Third iteration

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
  • Using for Loop
  • Using Function
  • Using Recursion

Using While Loop

SumOfDigitExample1.java

Output:

Enter the number: 876
Sum of Digits: 21

Using for Loop

SumOfDigitsExample2.java

Output:

Enter a number: 3456788
Sum of digits: 41

Using Function

SumOfDigitsExample3.java

Output:

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.

SumOfDigitsExample4.java

Output:

The sum of digits: 35

Using Recursion

SumOfDigitsExample5.java

Output:

The sum of digits: 28

Let's create another Java program for the same.

SumOfDigitsExample6.java

Output:

Enter a number: 983451
The sum of digits: 30






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA