The code should print something like this:
Now Number = 388
Initial Number:388
Sum = 19
Now Number = 19
Sum = 10
Now Number = 10
Sum = 1
Now let's Have a look at the code:
public class SumOfDigits {
public static void main(String[] args) {
int num = 388;
int numOfDigits[] = calculateNumberOfDigits(num) ;
System.out.println("Initial Number:" + num);
while (numOfDigits.length>1){
int sum = 0;
for (int i = 0; i < numOfDigits.length; i ++){
sum = sum + numOfDigits[i];
}
System.out.println("Sum = " + sum);
if(sum < 10){
break;
}
numOfDigits = calculateNumberOfDigits(sum);
}
}
public static int[] calculateNumberOfDigits(int num){
System.out.println("Now Number = " + num);
int numOfDigits = 0;
int digits[] = new int[100];
while(num>0){
digits[numOfDigits] = num%10;
num = num/10;
numOfDigits = numOfDigits +1;
}
return digits;
}
}
No comments:
Post a Comment