C Program to Find Given Number is Armstrong or Not

Armstrong number is a number, it is equal to the sum of the cubes of each digit in the same number.

Let us see an example for Armstrong Number,

153 is Armstrong number

13 + 53 + 33 

1 + 125 + 27 = 153

We have very few Armstrong numbers between 1 to 1000, they are, 1, 153, 370, 371, 407

/*C Program to check given number is ARMSTRONG or not */

#include<stdio.h>
int main()
{
    int num,r,temp;
    int sum=0;

    printf("Enter any number to check Armstrong:");
    scanf("%d",&num);

    temp=num;
    while(num!=0)
    {
        r=num%10;
        num=num/10;
        sum=sum+(r*r*r);
    }
    if(sum==temp)
        printf("%d is an Armstrong number",temp);
    else
        printf("%d is not an Armstrong number",temp);

    return 0;
}

The trace of Armstrong number:


Loop 1: num!=0 is true

take the digit by digit by using num%10

r= 153%10=3

find the remaining number using num/10, here num=153

num=153/10 = 15 (num replaced with 15)

sum=0+(3*3*3)=27


Loop 2: num!=0 is true

r= 15%10 =5

num=15/10=1 (num is replaced with 1)

sum=27+ (5*5*5) = 152


Loop 3: num!=0 is true

r=1%10 =1

num=1/10 =0 (num is replaced with 0)

sum =152+(1*1*1) = 153


Loop 4: num!=0 is false

terminates loop, and compare this sum with temp value. If both are same, it is an Armstrong number.


OUTPUT:

Enter any number to check Armstrong: 153
153 is an Armstrong number

Leave a Reply

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