Sum of Digits of a Number in Java
Overview
Adding the digits of a number is one of the most basic programs. The concept involved here helps in understanding how loops function. If we have a number and we need to find the sum of its digits, the simplest method is to divide it into digits and add each in integer form.
There can be a few ways to find the sum of digits of a number in java. We'll go through those methods in this article.
Steps to Find the Sum of Digits of a Number in Java
Input any integer number (or the number can be taken by own). After that, we will apply the modulus and division operations to determine the sum of the digits of the number. Let's look at the steps.
- Firstly, we initialize the variable with the number. We also initialize a variable sumOfDigits as .
- Next, we will find the remainder using the modulo operator, which will give us the last digit of the number.
- After that, we will constantly add the obtained digit(remainder) to the sumOfDigits variable.
- At the same time, we also need to divide the number by , which removes the last digit of the number.
- Repeat steps – until the number is equal to .
Sum of Digits of a Number in Java
By using for loop The for loop iterates until , then add the remainder of to the sumOfDigits until is false. If , the for loop is interrupted, and the sum is printed.
Output:
Sum of Digits of a Number in Java By using Function
We can also make our code more modular and organized by putting it inside a function. The function can be called from anywhere, and it will return the sum of digits, and we need not write its implementation again and again.
Output:
Sum of Digits of a Number in Java By using Recursion
Sum of digits of a number can also be calculated with the help of recursion. Here we will use as the base condition.
The function will keep on calling itself till the base condition is met. Each time the last digit is chopped, the result from the remaining number is used again to calculate the remaining sum recursively.
In the program given below, the above conditions are written with the help of a ternary operator. If the number is not zero, run the code after the colon (:) in the ternary operator; otherwise output 0. The procedure sumOfDigits() is called recursively.
Output:
Sum of Digits of a Number in Java By using Command Line Arguments
Now, to calculate the sum of the digits of a number, we'll use command line arguments. The main method's "String args[]" will receive the command line parameters. We transform the value at index 0 to long using Long.parseLong(arg[0]), where Long is the wrapper class.
Output:
Conclusion
- Adding the digits of a number means splitting the number into digits and adding each of them to obtain the result.
- To find the sum of digits of a number in java, we discussed four ways: using for loop, function, recursion, and command line arguments.