Sum of Digits of a Number in JavaIn 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. Steps to Find the Sum of Digits of a Number in JavaEnter 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. 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 NumberThere are the following ways to find the sum of digits of a number:
Using While LoopSumOfDigitExample1.java Output: Enter the number: 876 Sum of Digits: 21 Using for LoopSumOfDigitsExample2.java Output: Enter a number: 3456788 Sum of digits: 41 Using FunctionSumOfDigitsExample3.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 RecursionSumOfDigitsExample5.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 Next TopicSum of Numbers in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India