231k views
4 votes
Consider the method digitSum below, which takes a positive integer parameter as input.

public int digitSum(int num)
{
int total = 0;
while (num > 0)
{
total += num % 10;
num /= 10;
}
return total;
}
Which of the following code segments could replace the while loop in the method digitSum without changing the value returned by the method?
I.
for (int h = 0; h < num; h++)
{
total += num % 10;
num /= 10;
}
II.
for (int j = num; j > 0; j--)
{
total += j % 10;
}
III.
for (int k = num; k > 0; k /= 10)
{
total += k % 10;
}
A. I only
B. II only
C. III only
D. I and II
E. II and III

User Cheryll
by
9.0k points

1 Answer

3 votes

Final answer:

Option III is the only correct replacement for the while loop in the digitSum method since it follows the same logic of adding the last digit and dividing num by 10 on each iteration. Options I and II do not properly iterate through the digits of num.

Step-by-step explanation:

The student has asked which code segment could replace the while loop in the digitSum method without changing the returned value. The original loop iterates until num is greater than 0, adding the last digit of num to total and then dividing num by 10 in each iteration.

Only option III matches this behavior. It iterates as long as k is greater than 0, adding the last digit of k to total and then dividing k by 10 in each iteration. Option I is incorrect because it iterates num times, which is not related to the number of digits in num. Option II is incorrect because the loop variable j is never divided by 10; thus it doesn't move to the next digit in each iteration.

Correct Answer: C. III only

User Aramakus
by
7.9k points