Skip to content
Programming Loops and patterns
All classes Beginner About 12 min Premium

Adding the digits of a number

Choose a number and watch a while loop take it apart: % 10 gives the last digit, dividing by 10 drops it, and the loop adds each digit to a total until the number reaches 0. Count the digits on the way.

Core concept

n % 10 is the last digit of n and floor(n / 10) is n without it, so a while loop that repeats both until n is 0 visits every digit once

Topic: Loops and patterns

Every whole number is made of digits: 2081 has the digits 2, 0, 8 and 1. A program can take a number apart one digit at a time with two tricks. The remainder n % 10 is the last digit, because 2081 = 208 × 10 + 1. And floor(n / 10) drops that digit, leaving 208. A while loop: Steps that repeat, either a set number of times or until something becomes true. All key words repeats the two tricks while n is more than 0, adding each digit to a total (an accumulator) and adding 1 to a counter. When n reaches 0 there are no digits left, the condition: A question with a yes or no answer that decides what the program does next. All key words is false and the loop stops. We do not need to know how many digits there are first: the loop finds out.

Key words explained

What you will learn

  • Use % 10 to get the last digit and floor(n / 10) to drop it.
  • Trace a while loop that stops when n reaches 0.
  • Use an accumulator for the sum and a counter for the digits.
  • Predict how many times the loop repeats.

Before you start

  • Know place value: ones, tens, hundreds.

Materials

  • A notebook to trace the loop

Equipment

  • None

Procedure

  1. Step through the program for 405.
  2. Run it for 2081 and for 98765.
  3. Try 7, a number with one digit.
  4. Answer the practice challenges.
Premium experiment Create a free account