Program to find out sum of digits

🔢 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)

  1. Start with a number, say a = 111.

  2. Initialize sum = 0.

  3. 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

  4. When a becomes 0, print the sum.


🧠 Example Walkthrough

Let’s trace the steps for a = 111:

Stepa    a % 10 (digit)    sum after addition    a / 10 (next a)
1111            1            1            11
211            1            2            1
31            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

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts