## Java code for adding all digits of a given number

**Problem Definition :-** Write a java code to find out the sum of all digits of a given number.

**Solution :-**

**Step 1:** Classes that are required in coding.

**MainClass.java** - contains **main() method**.

**SumDigits.java** - contains **calculateSumOfDigits() method** in which business logic is written.

**Step 2: **Variables required in MainClass.java class

**readNumber **of type **integer** - purpose is to read number from user during run time.

Variables required in SumDigits.java class

**sum and quotient,** both of type **integer**. Purpose of sum variable is to store sum of all digits and that of quotient is to store quotient when number is divided by 10. Why divide by 10, is explained later

**Step 3: ****Method** required in **SumDigits.java class** is **calculateSumOfDigits()** in which actual business logic is written.

**Step 4:** Actual code,

In MainClass.java, object sumDigits of a SumDigits class is created and by using object of Scanner class, required number is read.

In SumDigits.java class, number that is read during run time is passed through calculateSumOfDigits() method. This number is divided by 10 to get one less digit (of unit's place) every time. Then the modulus is done on same number by using % with 10 which gives remainder and this remainder is same as that the number in unit's place of original number. And, ultimately that remainder is added every time when modulus is done. Here, remainder is stored in number variable and added with sum number. And then qoutient which was obtained using divide by 10, is again assigned to number variable for further division.

Following is its execution.

Like it on Facebook, Tweet it or share this article on other bookmarking websites.

## Comments (0)