Java Program to Add Digits of a Number

In this post, we will learn how to add digits of a number using Java Programming language. So, let’s see the Java Program to add digits of a number.

Java Program to Add Digits of a Number

import java.util.*;

public class Main{
    
    public static void main(String[] args){
        
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number : ");
        int number = sc.nextInt();
        
        int num = number;
        int sum = 0;
        
        while(num!=0){
            int digits = num%10;
            sum += digits;
            num /= 10;
        }
        
        System.out.println("Sum of the digits of "+number+" is "+sum);
    }
    
}

Output

Enter the number: 9999
Sum of the digits of 9999 is 36

How Does This Program Work ?

In this program, we first input the number using Scanner Class in Java. Then we initialize a sum variable with 0.

while(num!=0){
   int digits = num % 10;
   sum += digits;
   num /= 10;
 }

We calculate the product of digits using a simple while loop.

Note : sum += digits, where += is a shorthand operator, which means sum = sum + digits.

After 1st iteration, add = 0 + 4 = 4, num becomes 123.
After 2nd iteration, add = 4 + 3 = 7, num becomes 12.
After 3rd iteration, add = 7 + 2 = 9, num becomes 1.
After 4th iteration, add = 9 + 1 = 10, num becomes less than 0 and loop terminates.

System.out.println("Sum of the digits of "+number+" is "+sum);

Then, we print the results i.e. The sum of the digits. Hence, this is How to code the Java Program to Add Digits of a Number.

Conclusion

I hope after going through this post, you understand how to code Java Program to Add Digits of a Number.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *