🔢 Find the Sum of Digits of a Number (Java)
🧩 What problem are we solving?
We often need to find the sum of digits in a number — for example, to check whether a number is divisible by 3 or 9, or as a simple exercise in integer manipulation.
Given a number (like 111), the goal is to extract each digit, add them together, and display the total.
For 111, the result is 1 + 1 + 1 = 3.
⚙️ How it works (step by step)
-
Start with a number, say
a = 111. -
Initialize
sum = 0. -
Repeat while
a > 0:-
Get the last digit using the modulo operator:
d = a % 10 -
Add it to
sum:sum = sum + d -
Remove the last digit from the number using integer division:
a = a / 10
-
-
When
abecomes0, print the sum.
🧠Example Walkthrough
Let’s trace the steps for a = 111:
| Step | a | a % 10 (digit) | sum after addition | a / 10 (next a) |
|---|---|---|---|---|
| 1 | 111 | 1 | 1 | 11 |
| 2 | 11 | 1 | 2 | 1 |
| 3 | 1 | 1 | 3 | 0 |
✅ Final sum = 3
Main program
package com.vinod.test;
/**
*@authorvinodkariyathungalkumaran
*
*/
public class FindSumOfDigits {
public static void main(String[] args) {
{
int sum, d;
int a = 111;
sum = 0;
for (int i = 1; i <= 10; i++) {
d = a % 10;
a = a / 10;
sum = sum + d;
}
System.out.println("Sum of Digit =" + sum);
}
}
}
Ouput
Sum of Digit =3
No comments:
Post a Comment