w3resource
Java Programming Exercies

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?



New Content: Composer: Dependency manager for PHP, R Programming