Problem Statement
Write a Java program to find the sum of digits of a number entered by the user.
—
Input
A number like:
1234
—
Output
A message like:
Sum of digits = 10
—
What Does “Sum of Digits” Mean?
You break the number into single digits and add them all together:
1234 →
1 + 2 + 3 + 4 = 10
That’s the sum of digits!
Java Code
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
// Step 1: Ask the user for a number
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a number: “);
int number = scanner.nextInt();
int sum = 0;
int temp = number;
// Step 2: Break the number into digits and add them
while (temp > 0) {
int digit = temp % 10; // Get last digit
sum += digit; // Add to sum
temp = temp / 10; // Remove last digit
}
// Step 3: Show the result
System.out.println(“Sum of digits = ” + sum);
}
}
Step-by-Step (Explained Like You’re New)
1. We take a number from the user.
2. We use % 10 to get the last digit.
3. We add that digit to a variable called sum.
4. Then we use / 10 to remove the last digit.
5. We repeat this until there are no digits left.
6. Finally, we show the total sum.
—
Example
Input: 567
Calculation: 5 + 6 + 7 = 18
✅ Output: Sum of digits = 18
—
Challenge for You
Try to write the same program using a String, by looping through each character and converting it to a number using Character.getNumericValue()!
—
Come back tomorrow for Challenge #6!
One small Java program a day = Big progress over time.

