Home Lifestyle Sum of Digits Until Single Digit in Java Language

# Sum of Digits Until Single Digit in Java Language

32
0 Sum of Digits Until Single Digit in Java Language – we will find the sum of digits until the single digit in Java. Previously we have developed a Java program to find the sum of digits of the number. But now we will find the sum of digits until the number becomes single digit,

• Example:- number = 123456
• => The sum of digits of 123456 = 1+2+3+4+5+6 = 21
• => The number 21 is of two digits number so again we will find the sum of digits of the number,
• => The sum of digits of 21 = 2+1 = 3
• Now, 3 is single-digit so it is the digital sum of the number 123456.

## Sum of Digits Until Single Digit in Java Language

``````import java.util.Scanner;

public class DigitalSum {

// method to find sum of digits
// of a given number
public static int sumOfDigits(int number) {

// declare variables
int lastDigit = 0;
int sum = 0;

// loop to repeat the process
while(number != 0) {
// find last digit
lastDigit = number % 10;
// add last digit to sum
sum = sum + lastDigit;
// remove last digit
number = number / 10;
}

// sum value is the sum of digits
// of the given number
return sum;
}

// method to find digital sum
public static int digitalSum(int number) {
int result = number;
while(result / 10 != 0) {
result = sumOfDigits(result);
}
return result;
}

public static void main(String[] args) {

// declare variables
int number = 0;
int sumOfDigitsUntilSingle = 0;

// create Scanner class object
Scanner scan =  new Scanner(System.in);
System.out.print("Enter an integer number:: ");
number = scan.nextInt();

// find sum of digits of number
sumOfDigitsUntilSingle = digitalSum(number);

// display result
System.out.println("The sum of digits until" +
" single digit of the number "+number+
" = "+sumOfDigitsUntilSingle);

// close Scanner class object
scan.close();
}
}

``````

## OUTPUT

``````
Enter an integer number:: 123456
The sum of digits until single digit of the number 123456 = 3

Enter an integer number:: 456
The sum of digits until single digit of the number 456 = 6
``````