Sum of digits of a number using Java

Sum of digits of a number

In this article we will find the sum of digits of an integer. For this purpose we will use a loop and a variable to sum the digits of the number entered by the user. Let us consider some examples for better understanding :

Input : 27

Output : Sum of Digits = 9

Input : 12345

Output : Sum of Digits = 15

So, now we create a java program to calculate the sum of digits of a given number.

Algorithm

Step 1 : Ask the user to enter an integer and store that integer value in a variable, number.

Step 2 : Declare a variable sum and initialize it with 0.

Step 3 : Use a while loop to pick the digits of the integer and count the number of digits one by one.

Step 4 : Use a statement to pick the last digit of the integer.

Step 5 : Perform addition and store it in variable sum

Step 6 : Restore the value of number by removing last digit in every iteration of the loop.

Step 7 : Repeat the Steps from 3 to 6 till the value of number becomes 0.

Step 8 : Display the value of sum.

sum of digits of a number in java

Code in Java :

//Java program to calculate sum of digits of a number
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
//declare a variable to store sum of digits
int sum= 0;
while(number != 0)
{
int pick_last = number % 10;
sum = sum + pick_last;
number = number / 10;
}
//display sum of digits
System.out.print("Sum of Digits = "+sum);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a number : 123
Sum of Digits = 6