Introduction
In programming, working with numbers is a fundamental skill. One common problem asked in exams, interviews, and basic coding practice is finding the sum of digits of a number.
For example:
Input: 1234
Output: 1 + 2 + 3 + 4 = 10
In this article, you’ll learn:
Logic behind the program
Step-by-step explanation
Java implementation
Dry run example
π§ Concept Behind Sum of Digits
To find the sum of digits, we repeatedly:
Extract the last digit of the number
Add it to a sum variable
Remove the last digit from the number
Key Operations:
n % 10→ gives the last digitn / 10→ removes the last digit
π» Java Program
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
while (num > 0) {
int digit = num % 10; // Extract last digit
sum = sum + digit; // Add to sum
num = num / 10; // Remove last digit
}
System.out.println("Sum of digits = " + sum);
}
}
π Step-by-Step Explanation
Let’s break down the logic:
Input the number
User enters a number like
1234
Initialize sum
sum = 0
Loop until number becomes 0
Extract digit using
%Add it to
sumRemove digit using
/
Print result
π§ͺ Dry Run Example
Input: 1234
| Step | num | digit (num % 10) | sum |
|---|---|---|---|
| 1 | 1234 | 4 | 4 |
| 2 | 123 | 3 | 7 |
| 3 | 12 | 2 | 9 |
| 4 | 1 | 1 | 10 |
| End | 0 | — | 10 |
Output: Sum = 10
⚡ Alternative Approach (Using String)
You can also solve this by converting the number into a string:
public class SumDigitsString {
public static void main(String[] args) {
String num = "1234";
int sum = 0;
for (int i = 0; i < num.length(); i++) {
sum += num.charAt(i) - '0';
}
System.out.println("Sum of digits = " + sum);
}
}
π Key Points to Remember
%operator extracts digits/operator reduces the numberLoop continues until number becomes zero
Works for any positive integer
π― Conclusion
The sum of digits problem is simple but very important for building logic in programming. It helps you understand loops, arithmetic operations, and number manipulation.
Once you master this, you can move on to advanced problems like:
Sum of even/odd digits
Product of digits
Palindrome numbers
Comments
Post a Comment