Math Fundamentals18 sections · 814 units
Open in Course

Add Digits - Loop Approach

Straightforward method

The direct approach: while n10n \geq 10, extract each digit using nmod10n \bmod 10, add them up, and repeat with the sum.

For n=38n = 38: extract 88 and 33, sum is 1111. For n=11n = 11: extract 11 and 11, sum is 22. Now n<10n < 10, so return 22.

This works but takes multiple iterations. There's a faster way using modulo arithmetic.