w3resource

Java: Accept a positive number and repeatedly add all its digits until the result has only one digit


Sum Digits to Single Digit

Write a Java program to accept a positive number and repeatedly add all its digits until the result has only one digit.

Visual Presentation:

Java Basic Exercises: Accept a positive number and repeatedly add all its digits until the result has only one digit.


Sample Solution:

Java Code:

// Importing necessary Java utilities
import java.util.*;

// Main class Solution
public class Solution {
    // Main method
    public static void main(String[] args) {
        // Creating Scanner object for user input
        Scanner in = new Scanner(System.in);
        
        // Prompting user to input a positive integer
        System.out.print("Input a positive integer: ");
        
        // Reading the input value provided by the user
        int n = in.nextInt();
        
        // Checking if the input is a positive integer
        if (n > 0)
            // Printing the result of add_digits_until_one method if the input is positive
            System.out.println(add_digits_until_one(n));
    }

    // Method to add digits of a number until the result becomes a single digit
    public static int add_digits_until_one(int n) {
        // Loop to keep adding digits until the number becomes a single digit
        while (n > 9) {
            int sum_digits = 0;
            
            // Loop to extract digits and calculate their sum
            while (n != 0) {
                sum_digits += n % 10; // Adding the last digit to sum
                n /= 10; // Removing the last digit
            }
            n = sum_digits; // Assigning the sum to 'n' for next iteration
        }
        return n; // Returning the single-digit sum
    }
} 

Sample Output:

Input a positive integer:  25
7

Flowchart:

Flowchart: Java exercises: Accept a positive number and repeatedly add all its digits until the result has only one digit.



For more Practice: Solve these Related Problems:

  • Write a Java program to repeatedly multiply the digits of a number until a single digit is obtained.
  • Write a Java program to recursively compute the digital root of a given number.
  • Write a Java program to extract all digits from an input string, sum them, and reduce the result to a single digit.
  • Write a Java program to sum the digits of a number repeatedly while skipping zeros until only one digit remains.

Go to:


PREV : Check Identical Binary Trees.
NEXT : Longest Consecutive Path in Tree.

Java Code Editor:

Company:  Adobe Microsoft

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.