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)

The output of the example looks like this:

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.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer