Sum of digits in a number
This program is much similar to this one: Find product of digits in a number. The only difference is instead of multiply we have to perform addition here.
Logic
First of all, we are declaring one variable sum with value 0, we are going to use this variable to store the sum of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.
The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to add it into variable sum and store the result again in variable sum.
After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simply print the variable sum containing the sum of all digit.
Program
import java.util.Scanner; public class DigitSum { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num, temp, sum = 0; // Take numbers from user System.out.print("Enter any number : "); num = scanner.nextInt(); // Store to temporary variable. temp = num; while(temp != 0) { sum += temp % 10; // Remove last digit of 'temp' temp /= 10; } System.out.println("\nSum of all digits in " + num + " : " + sum); } }
Output
Enter any number : 123456
Sum of all digits in 123456 : 21