What are Armstrong Numbers and Digit Sums- C Programming For Beginners

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Free C Programming Course • Chapter 5 • Lecture 16

Armstrong Numbers and Digit Sums

Two classic digit-processing programs, rewritten from scratch for our free embedded C course, with traces, outputs, and checksum thinking.

This lecture of our free C programming course applies everything from loops so far: the % and / digit trick, nested loops, and loop conditions. We solve two famous exercises, Armstrong numbers and the repeated digit sum, and then connect them to checksum ideas used in embedded C programming. It is a practical free C tutorial for building loop confidence.

What You Will Learn

  • What an Armstrong number is and how to test one with a nested loop.
  • How to generalise the test to any number of digits.
  • How to reduce a number to a single digit by repeated digit sums.
  • A closed-form shortcut to cross-check your loop.
  • Where digit and checksum logic appears in firmware.

Prerequisites

Complete the nested loops lecture first. You should be comfortable with the remainder operator %, integer division, while loops, and calling a small function.

The Digit Extraction Toolkit

Both problems need individual digits. In decimal, n % 10 returns the last digit and n / 10 discards it. Repeat until the number becomes zero and you have visited every digit from right to left.

Digit Extraction Loop
d = n % 10 use d n = n / 10 n > 0 ? repeat n == 0 : all digits done

What Is an Armstrong Number?

An Armstrong number, also called a narcissistic number, equals the sum of its own digits each raised to the power of the number of digits. For three-digit numbers the power is 3. Take 153: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153, so it qualifies. The number 371 works as well, since 27 + 343 + 1 = 371.

NumberDigitsPowerSum of powersArmstrong?
153331 + 125 + 27 = 153Yes
3703327 + 343 + 0 = 370Yes
123331 + 8 + 27 = 36No
9474446561 + 256 + 2401 + 256 = 9474Yes

Finding Three-Digit Armstrong Numbers

The plan uses two loops. The outer for tries every candidate from 100 to 999. For each candidate, an inner while loop extracts the digits from a copy and accumulates the cubes. Working on a copy matters, because we must still have the original candidate to compare against.

#include <stdio.h>

static unsigned ipow(unsigned base, int exp)
{
    unsigned r = 1;
    for (int i = 0; i < exp; i++)
        r *= base;
    return r;
}

int main(void)
{
    puts("3-digit Armstrong numbers:");
    for (int cand = 100; cand <= 999; cand++)
    {
        int rest = cand, cubes = 0;
        while (rest > 0)
        {
            int d = rest % 10;
            cubes += d * d * d;
            rest /= 10;
        }
        if (cubes == cand)
            printf("%d ", cand);
    }
    printf("\n\nGeneral n-digit check up to 10000:\n");
    for (unsigned v = 1; v <= 10000; v++)
    {
        int len = 0;
        for (unsigned t = v; t > 0; t /= 10)
            len++;
        unsigned s = 0;
        for (unsigned t = v; t > 0; t /= 10)
            s += ipow(t % 10, len);
        if (s == v && v >= 10)
            printf("%u ", v);
    }
    printf("\n");
    return 0;
}

Build and Run

$ gcc -std=c17 -Wall -Wextra -o arm arm.c
$ ./arm
3-digit Armstrong numbers:
153 370 371 407

General n-digit check up to 10000:
153 370 371 407 1634 8208 9474 

Understanding the Two Parts

The first part is the textbook shape: an outer loop of 900 candidates and an inner loop that runs three times for each. The second part removes the assumption of three digits. A first loop counts the digits into len, and a second loop raises each digit to the power len. We start the search from 10 in the printout because every single-digit number trivially equals itself and is usually excluded. The result matches the first one for three digits, and also finds 1634, 8208, and 9474.

Checking Candidate 153
rest = 153, d = 3, cubes = 27 rest = 15, d = 5, cubes = 152 rest = 1, d = 1, cubes = 153 rest = 0, stop cubes == 153, print it

Repeated Digit Sum Until One Digit Remains

Take 789988. Its digits add up to 49. That still has two digits, so add again: 4 + 9 = 13. Again: 1 + 3 = 4. A single digit, so we stop. The sequence is 789988, 49, 13, 4. The outer loop repeats while the value has more than one digit, and the inner loop performs one round of digit summing.

#include <stdio.h>

int main(void)
{
    unsigned long n = 789988;
    printf("%lu", n);
    while (n > 9)
    {
        unsigned long s = 0;
        for (unsigned long t = n; t > 0; t /= 10)
            s += t % 10;
        printf(" -> %lu", s);
        n = s;
    }
    printf("\n");
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o root root.c
$ ./root
789988 -> 49 -> 13 -> 4
Shrinking 789988 to One Digit
789988 7+8+9+9+8+8 49 4+9 13 1+3 4

A Shortcut to Verify Your Loop

The result of this repeated sum is called the digital root. For any positive integer n it equals 1 + (n - 1) % 9. Check it: (789988 - 1) % 9 is 3, and adding 1 gives 4, which matches our loop. A closed-form formula is a handy way to test a loop-based answer. Keep in mind that the loop teaches you the technique, while the formula is the efficient route.

Digits and Checksums in Embedded Systems

Digit-wise processing appears in firmware more often than beginners expect. Converting a number to text for a 7-segment display or a UART message is the same % 10 and / 10 loop. Many identification schemes, such as card numbers and product codes, validate a number using digit sums and weights. Simple checksums on received frames add up bytes in a loop in the same spirit. When you later write a driver that prints a sensor value without printf, you will reuse exactly this pattern.

TechniqueWhere it shows up
Digit extraction with % and /Number to display digits, itoa-style conversion
Digit sumSimple validation codes
Byte sum in a loopFrame checksums on serial links
Powers by repeated multiplicationFixed-point scaling without floating point

Common Mistakes and Troubleshooting

  • Modifying the original. If you divide the candidate itself, the final comparison is against zero. Always work on a copy.
  • Wrong power. Cubing works only for three-digit numbers. For other lengths count the digits first.
  • Integer overflow. Large numbers overflow int when digits are raised to high powers. Use unsigned long or uint64_t.
  • Floating-point pow(). The pow() function returns a double and may be off by a tiny amount. A small integer loop is exact.
  • Treating zero specially. A digit loop on 0 never runs, so handle the value 0 before the loop if it is a valid input.

Best Practices

  • Break the problem into digit extraction, then the test, then output.
  • Move the digit test into a function such as is_armstrong() once the idea is clear.
  • Use unsigned types for digit work so negative remainders cannot surprise you.
  • Print the intermediate values while debugging, as the digital root program does.

Summary and Key Takeaways

  • n % 10 gives the last digit and n / 10 removes it.
  • An Armstrong number equals the sum of its digits raised to the digit count.
  • A nested loop pair tests many candidates: outer for candidates, inner for digits.
  • Repeating the digit sum gives the digital root, which also equals 1 + (n - 1) % 9.
  • The same digit loop converts numbers to display text in embedded C.

Now that you can process digits, you are ready for the dangerous side of loops, which is the subject of the next lecture in our free embedded C programming series: infinite loops.

Frequently Asked Questions

What are the three-digit Armstrong numbers?

They are 153, 370, 371 and 407, as confirmed by the program above.

Is every single-digit number an Armstrong number?

By the definition each equals its own digit to the power one, so yes. Courses usually start searching from 10 or 100 to avoid listing them.

Why work on a copy of the number?

The digit loop destroys its variable by dividing it down to zero. You need the original for the final comparison.

Should I use pow() from math.h?

For exact integer results prefer a small multiplication loop. pow() returns a double and can introduce rounding errors, and it needs the math library on some embedded toolchains.

What is the digital root?

It is the single digit reached by repeatedly adding the digits of a number. For positive n it equals 1 plus (n minus 1) modulo 9.

How is digit extraction used in embedded systems?

To show numbers on 7-segment displays and LCDs, and to build text messages for a UART when printf is too large for the device.

Free C Programming Course: Next Lecture

Learn how loops go wrong, and how embedded programmers use endless loops on purpose, in the next lecture.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *