Hello
This is how i calculated the digital root of an integer.
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
int sum = 0;
while (true)
{
if (num > 0)
{
int dsum = num % 10;
num /= 10;
sum += dsum;
}
else if (sum > 9)
{
int dsum = sum % 10;
sum /= 10;
sum += dsum;
} else if (sum <= 9 ) break;
}
println("Digital Root is: " + sum);
}
The program works fine.
Is there a better/shorter way of calculating the digital root of a number. ?
EDIT/ADDED : Here is the implementation of the above problem by using Tyler's answer, it works as well:
import acm.program.*;
public class Problem7 extends ConsoleProgram
{
public void run()
{
println("This program calculates the digital root of an interger.");
int num = readInt("Enter the number: ");
println("Digital Root of " + num + " is: " + (1 + (num - 1) % 9));
}
}