OverIQ.com

C Program to find Armstrong numbers

Last updated on July 27, 2020


What are Armstrong numbers? #

Armstrong number is a 3-digit number such that the sum of the cube of each of its digits is equal to the number itself. For example:

1
2
3
4
153 = 1^3 + 5^3 + 3^3 = 153
370 = 3^3 + 7^3 + 0^3 = 370
371 = 3^3 + 7^3 + 1^3 = 371
407 = 4^3 + 0^3 + 7^3 = 407

The following is a C program find all the Armstrong numbers between 100 and 999:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**************************************************************
 * Program to find the Armstrong numbers between 100 and 999 
***************************************************************/

#include <stdio.h>

int main() 
{

    int num, sum, rem;

    for(int n = 100; n < 999; n++)
    {
        num = n;
        sum = 0;
        while(num != 0)
        {
            rem = num % 10;     // get the last digit  |  sum += rem * rem * rem;  // cube the remainder and add it to the sum  |  num = num / 10;    // remove the last digit
        }

        if(n == sum)
        {
            printf("%d is an Armstrong number\n", n);
        }
    }

    return 0;
}

Expected Output:

1
2
3
4
153 is an Armstrong number
370 is an Armstrong number
371 is an Armstrong number
407 is an Armstrong number

How it works: #

The following table demonstrates what happens at each iteration of the while loop (assuming the n = 153):

Iteration rem sum num
After 1st iteration rem = 153%10 = 3 sum = 0 + 3^3 = 27 num = 153 / 10 = 15
After 2nd iteration rem = 15%10 = 5 sum = 27 + 5^3 = 152 num = 15 / 10 = 1
After 3rd iteration rem = 1%10 = 1 sum = 152 + 1^3 = 153 num = 1 / 10 = 0

Recommended Reading: