Unit 2 Cycle 2 Day 19: Loop Algorithm: Digit Sum

Unit 2 Advanced (Cycle 2) Day 19 of 28 Advanced

Loop Algorithm: Digit Sum

Section 2.10 — Loop Algorithms

Key Concept

The digit sum algorithm repeatedly extracts the last digit of a number using n % 10, adds it to a running total, then removes the last digit using n /= 10. The loop continues while n > 0. This is a classic AP exam algorithm that tests your understanding of modulo and integer division working together. Variations include computing the product of digits, counting specific digits, or reversing a number. The key is recognizing that % 10 isolates the last digit and / 10 shifts all digits right.

Consider the following code segment.

int n = 9876; int digitSum = 0; while (n > 0) { digitSum += n % 10; n /= 10; } System.out.println(digitSum);

What is printed as a result of executing the code segment?

Answer: (A) 30

Extract and sum each digit: n=9876: 6 (sum=6), n=987. n=987: 7 (sum=13), n=98. n=98: 8 (sum=21), n=9. n=9: 9 (sum=30), n=0. Loop ends. digitSum = 6+7+8+9 = 30.

Why Not the Others?

(B) 9876 is the original number, not the sum of its digits.

(C) 24 would be 6+7+8+3, using the wrong digit for the thousands place.

(D) 6 is only the first digit extracted (ones place), not the total sum.

Common Mistake

n % 10 extracts the last digit. n /= 10 removes the last digit. Together in a loop, they process every digit right-to-left. The sum of digits of 9876 is 9+8+7+6 = 30.

AP Exam Tip

The digit extraction loop (% 10 then / 10) is a fundamental algorithm. It processes digits from right to left. Recognize this pattern on sight.

Review this topic: Section 2.10 — Loop Algorithms • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.