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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * Calculate Sum of Digits of a Number * * Source: https://webrewrite.com * * 256 = 2 + 5 + 6 = 13 * 15 = 1 + 5 = 6 */ public class SumOfDigits { public static void main(String[] args) { int num = 256; int rem = 0; int sum = 0; //if num is greater than zero while(num > 0) { //Find remainder of a number rem = num % 10; //Add remainder to the sum variable sum = sum + rem; //Reduce the number num = num / 10; } System.out.println(sum); } } |
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.