Calculate Armstrong numbers in C

This is an example C program for calculating Armstrong numbers.

#include <stdio.h>

int main ()
{
    int i;
    for (i = 1; i < 999; i++) {
        int ones = i % 10;
        int tens = (i / 10) % 10;
        int hundreds = (i / 100) % 10;
        int armstrong;

        armstrong = ones * ones * ones;
        armstrong += tens * tens * tens;
        armstrong += hundreds * hundreds * hundreds;
        if (i == armstrong) {
            printf ("%d is an armstrong number.\n", i);
        }
    }
    return 0;
}

Download it here.

The output of the example looks like this:

0 is an armstrong number.
1 is an armstrong number.
153 is an armstrong number.
370 is an armstrong number.
371 is an armstrong number.
407 is an armstrong number.

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer