Find Sum of Digits of a Number – Java Code

Write a java program to find sum of digits of a number. Given an input number, we have to write a java code to calculate sum of digits of a number.

For example –

i)

Input : 256

Output : 13 (2+5+60

ii)

Input : 15

Output : 6 (1+5)

Find first and last position of a number in a sorted array

Binary search using recursion in java

Algorithm to Find Sum of Digits of a Number

*  To calculate sum of digits of a number, we have to first find last digit of the number using modulo division the number by 10 i.e. rem = num % 10.

* Add remainder (last digit) to sum variable i.e. sum = sum + rem.

* Remove last digit from a number by dividing the number by 10 i.e. num = num / 10.

* Repeat this step until number becomes 0.

Find sum of digits of a number

Find sum of digits of a number

 

Java Program to Find Sum of Digits of a Number

We have discussed the algorithm to calculate sum of digits of a number. Let’s write a java code to print sum of digits of a number.

 

Video tutorial : Java program to calculate sum of digits of a number

In this video tutorial, I have explained how to find sum of digits of a number.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.