Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › CONTROL FLOW
For n = 50724, copy the value into work and start sum at 0. The expression work % 10 reads the rightmost digit, so it gives 4 while work is 50724. Reading that value does not change work. If the loop condition is work > 0, the condition stays true forever, and every pass reads 4 again.
int n = 50724;
int work = n;
int sum = 0;
while (work > 0) {
int digit = work % 10;
sum += digit;
}What one statement makes this loop stuck on digit 4 advance to the next digit?
while (work > 0) {
int digit = work % 10;
sum += digit;
}Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
After reading the rightmost digit, integer division by 10 removes it from work. Starting with work = 50724, the first division produces 5072. The next remainder is therefore based on 5072, not on the original number. Repeating this pair of operations moves from the rightmost digit toward the leftmost digit.
| WORK BEFORE | DIGIT = WORK % 10 | WORK AFTER WORK /= 10 |
|---|---|---|
| 50724 | 4 | 5072 |
| 5072 | 2 | 507 |
| 507 | 7 | 50 |
| 50 | 0 | 5 |
| 5 | 5 | 0 |
The order matters. First calculate digit = work % 10 while work still contains the current number. Then divide work by 10 so the next iteration sees a smaller number. The extracted digits from n = 50724 appear in this order: 4, 2, 7, 0, 5.
work is a temporary copy that shrinks until the loop can stop. n remains 50724 throughout, while sum stores the result you are building. Keep those jobs separate: changing n would destroy the original input, and using work as the answer would lose the number needed to find the next digit.
int n = 50724;
int work = n;
int sum = 0;
while (work > 0) {
int digit = work % 10;
sum += digit;
work /= 10;
}| ITERATION | DIGIT | WORK AFTER UPDATE | SUM AFTER ADDITION |
|---|---|---|---|
| start | - | 50724 | 0 |
| 1 | 4 | 5072 | 4 |
| 2 | 2 | 507 | 6 |
| 3 | 7 | 50 | 13 |
| 4 | 0 | 5 | 13 |
| 5 | 5 | 0 | 18 |
After three iterations for n = 50724, what are the values of work and sum?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
After the fifth iteration, work is 5, digit is 5, and sum becomes 18. The final update work /= 10 changes 5 to 0. On the next condition check, work > 0 is false, so the loop terminates. The value n is still 50724, work is 0, and sum is 18.
The zero in 50724 still consumes an iteration. When work is 50, work % 10 gives digit = 0, then work becomes 5. Adding that digit leaves sum at 13, but the iteration was necessary to remove the zero and advance to 5. A digit does not need to change the accumulator to count as processed.