DSA FUNDAMENTALS › CONTROL FLOW
You can process the positive integer 5072 from right to left by repeatedly reading its rightmost digit and shortening the working value. The remainder operation n % 10 gives the current rightmost digit. Integer division n / 10 removes that digit, because the fractional part is discarded. Starting with n = 5072, the digits arrive in the order 2, 7, 0, 5.
int n = 5072;
int sum = 0;
while (n > 0) {
int digit = n % 10;
n = n / 10;
}| BEFORE THE ITERATION, N | N % 10 | AFTER N / 10 |
|---|---|---|
| 5072 | 2 | 507 |
| 507 | 7 | 50 |
| 50 | 0 | 5 |
| 5 | 5 | 0 |
Given n = 5072, what do n % 10 and n / 10 produce?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The accumulator must include the new digit without losing the total from earlier iterations. With sum = sum + digit, the first digit changes sum from 0 to 2, the next changes it to 9, the zero leaves it at 9, and the last digit changes it to 14. Each assignment uses the old sum and adds one current digit.
int digit = n % 10;
sum = sum + digit;The shorter statement sum = digit does something different. It assigns the current digit directly to sum, replacing the previous total. For 5072, the values become 2, then 7, then 0, then 5, so the loop finishes with 5 instead of the digit sum 14. The digits were extracted, but the earlier results were discarded.
| CURRENT DIGIT | SUM = SUM + DIGIT | SUM = DIGIT |
|---|---|---|
| 2 | 2 | 2 |
| 7 | 9 | 7 |
| 0 | 9 | 0 |
| 5 | 14 | 5 |
The update n = n / 10 makes the loop condition n > 0 move toward false. The working value changes from 5072 to 507, then 50, then 5, then 0. Once n is 0, there is no digit left to process, so the loop stops.
If you omit n = n / 10, n stays equal to 5072. The condition n > 0 remains true forever, and n % 10 keeps producing 2. The accumulator may keep growing if it adds that digit, but the loop never reaches the state that permits termination.
while (n > 0) {
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}Repair this loop so it preserves every digit and eventually stops for n = 5072. Type the two replacement statements in order, separated by a newline.
while (n > 0) {
int digit = n % 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.
The complete loop first reads the current digit, then adds it to the accumulator, then reduces the working value. That order lets the loop use the current value of n before changing it. For 5072, the four iterations add 2, 7, 0, and 5, so the accumulator finishes at 14 exactly when n becomes 0.
int n = 5072;
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}| N AT START | DIGIT = N % 10 | SUM AFTER ADDITION | NEXT N = N / 10 |
|---|---|---|---|
| 5072 | 2 | 2 | 507 |
| 507 | 7 | 9 | 50 |
| 50 | 0 | 9 | 5 |
| 5 | 5 | 14 | 0 |