1. Introduction
In this tutorial, we are going to learn how to write a Java program to find the sum of the digits of a number. This is a common programming exercise and can be used in various scenarios such as checking the divisibility of a number, forming new numbers, or in number theory problems.
2. Program Steps
1. Define a class named SumOfDigits.
2. Inside the main method, declare and initialize an integer variable number with the number whose digits you want to sum.
3. Create a variable sum initialized to 0, which will store the sum of the digits.
4. Use a while loop to iterate through each digit of the number, adding each digit to sum until the number becomes 0.
5. Print the sum variable which will be the sum of digits of the given number.
cpublic class SumOfDigits { // Step 1: Define a class named SumOfDigits
public static void main(String[] args) { // Main method
// Step 2: Declare and initialize an integer variable number
int number = 12345;
// Step 3: Create a variable sum initialized to 0
int sum = 0;
// Step 4: Use a while loop to sum the digits
while (number != 0) {
sum += number % 10; // add the last digit to sum
number /= 10; // remove the last digit
}
// Step 5: Print the sum
System.out.println("Sum of digits: " + sum);
}
}
Output:
Sum of digits: 15
4. Step By Step Explanation
– Step 1: A class named SumOfDigits is defined.
– Step 2: An integer variable number is declared and initialized with a value whose digits we want to sum.
– Step 3: A variable sum is initialized to 0, which will hold the sum of the digits.
– Step 4: A while loop is used to iterate through each digit of the number. In each iteration, the last digit is added to sum, and then removed by dividing the number by 10.
– Step 5: The program prints the value of sum, which represents the sum of the digits in the original number.