Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: 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:

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

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:

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

Java Code Editor:

Company:  Adobe Microsoft

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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe