Sum digits of a number Java

Given an input integer as the number, our objective is to break down the number into it’s individual digits and sum them up together. To do so we’ll use the follow two operators,

  • Modulo Operator % : We’ll use this to extract the digits from the number.
  • Divide Operator / : We’ll use it to shorten the number by 1 digit.

Once we get the digits, we sum them up one by one with each iteration. Here are some of the methods to solve the above mentioned problem

Java is a versatile programming language. There are various methods through which we can calculate the sum of digits in Java. Let us discuss those methods in detail. Below given is a list which we would use to solve our problem.

Lets begin!

By using for loop

Programmers usually use loops to execute a set of statements. For loop is used when they need to iterate a part of the programs multiple times. It is particularly used in cases where the number of iterations is fixed!

Code:

class SumOfDigits
{
public static void main(String arg[])
{
long n,sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number ");
n=sc.nextLong();
for(sum=0 ;n!=0 ;n/=10)
{
sum+=n%10;
}
System.out.println("Sum of digits "+sum);
}
}

Output:
Enter a number
456
Sum of digits
15

The next segment tell you how to use static method to accomplish the goal.

By using static method

In Java, a static method is a method that belongs to a class rather than an instance of a class. The method is accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that member of a class.

Code:

class SumOfDigits
{
public static void main(String arg[])
{
long n,s;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number ");
n=sc.nextLong();
s=sum(n);
System.out.println("Sum of digits "+s);
}
static int sum(long num)
{
int sum=0;
while(num!=0)
{
sum+=num%10;
num/=10;
}
return sum;
}
}

Output:
Enter a number
678
Sum of digits
21

Let us now move to another method that is recursion.

By using recursion

Code:

import java.util.Scanner;
class SumOfDigits

{
int sum=0;
int sum(long num)
{

if(num!=0)
{
sum+=num%10;
num/=10;
sum(num);
}
return sum;
}

public static void main(String arg[])
{
long n,res;
SumOfDigits s=new SumOfDigits();
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number ");
n=sc.nextLong();

System.out.println("Sum of digits "+s.sum(n));

}
}

Output:
Enter a number
345
Sum of digits
12

Lastly, we will use command line arguments to calculate the sum of the digits of a number of a number.

By using command line arguments

Code:

class SumOfDigits
{
public static void main(String arg[])
{
long n,sum=0;
System.out.println("Enter a number ");
n=Long.parseLong(arg[0]);
while(n!=0)
{
sum+=n%10;
n/=10;
}
System.out.println("Sum of digits “ +sum);


}
}

Output:
Enter a number
123
Sum of digits
6

With this, we have reached towards the end of this tutorial on “Sum of Digits in Java “. I hope It helped you in some way. Keep reading, keep exploring! We will keep digging the Java world together. Stay tuned!

Make sure you practice as much as possible and revert your experience.  

This brings us to the end of our blog on “Java Program to find Sum of Digits in Java”.  I hope you found this blog informative and added value to your knowledge.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Sum of Digits in Java” article and we will get back to you as soon as possible.

This article covers a program in Java that find and prints the sum of all digits of a number entered by user. For example, if entered number is 13049, then the output will be 17. 17 is the sum of all digits of given number, i.e., 1+3+0+4+9.

Find Sum of Digits in Java using while Loop

The question is, write a Java program to find the sum of digits of a given number using while loop. The program given below is its answer:

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      int num, digit, sum=0;
      Scanner s = new Scanner(System.in);
      
      System.out.print("Enter a Number: ");
      num = s.nextInt();
      
      while(num!=0)
      {
         digit = num%10;
         sum = sum + digit;
         num = num/10;
      }
      
      System.out.println("\nSum of Digits = " +sum);
   }
}

The snapshot given below shows the sample run produced by above Java program, with user input 10349 as number to find and print the sum of its all digits:

java find sum of digits of number

That is, 1+0+3+4+9 is equal to 17. The same program can also be created in this way:

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      int num, digit, sum=0;
      Scanner s = new Scanner(System.in);
      
      System.out.print("Enter a Number: ");
      num = s.nextInt();
      
      System.out.print("\n");
      while(num!=0)
      {
         digit = num%10;
         sum = sum + digit;
         num = num/10;
         if(num!=0)
            System.out.print(digit + "+");
         else
            System.out.print(digit+ " = " + sum);
      }
   }
}

Here is its sample run with user input, 1309438:

find sum of digits of number java

Also the while block can be written in this way too:

while(true)
{
   digit = num%10;
   sum = sum + digit;
   num = num/10;
   if(num!=0)
      System.out.print(digit + "+");
   else
   {
      System.out.print(digit+ " = " + sum);
      break;
   }
}

Find Sum of Digits in Java using for Loop

Let's see how the same program looks like, when created using for loop.

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      int num, digit, sum;
      Scanner s = new Scanner(System.in);
      
      System.out.print("Enter a Number: ");
      num = s.nextInt();
      
      for(sum=0; num!=0; num = num/10)
      {
         digit = num%10;
         sum = sum + digit;
      }
      
      System.out.println("\nSum of Digits = " +sum);
   }
}

Find Sum of Digits using Function

This program is created using function. In this program, I've created a function named sumOfDigits() that takes a single argument and returns the sum of digits of that argument.