Java: Accept a positive number and repeatedly add all its digits until the result has only one digit
Java Basic: Exercise-183 with Solution
Write a Java program to accept a positive number and repeatedly add all its digits until the result has only one digit.
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in .nextInt();
if (n > 0)
System.out.println(add_digits_until_one(n));
}
public static int add_digits_until_one(int n) {
while (n > 9) {
int sum_digits = 0;
while (n != 0) {
sum_digits += n % 10;
n /= 10;
}
n = sum_digits;
}
return n;
}
}
Sample Output:
Input a positive integer: 25 7
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if two binary trees are identical or not. Assume that two binary trees have the same structure and every identical position has the same value.
Next: Write a Java program to find the length of the longest consecutive sequence path of a given binary tree.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join