Finding the digit root of a number
- by Jessica M.
Study question is to find the digit root of a already provided number. The teacher provides us with the number 2638. In order to find the digit root you have to add each digit separately 2 + 6 + 3 + 8 = 19. Then you take the result 19 and add those two digits together 1 + 9 = 10. Do the same thing again 1 + 0 = 1. The digit root is 1.
My first step was to use the variable total to add up the number 2638 to find the total of 19. Then I tried to use the second while loop to separate the two digits by using the %
I have to try and solve the problem by using basic integer arithmetic (+, -, *, /).
1.Is it necessary and or possible to solve the problem using nested while loops?
2.Is my math correct?
3. As I wrote it here it does not run in Eclipse. Am I using the while loops correctly?
import acm.program.*;
public class Ch4Q7 extends ConsoleProgram {
public void run(){
println("This program attempts to find the digit root of your number: ");
int n = readInt("Please enter your number: ");
int total = 0;
int root = total;
while (n > 0 ){
total = total + (n %10);
n = (n / 10);
}
while ( total > 0 ){
root = total;
total = ((total % 10) + total / 10);
}
println("your root should be " + root);
}
}