C program to check Armstrong number?

Problem statement

Write a program to take a number as an input from user and check whether the input number is Armstrong number or not, and print the output accordingly.

What is meant by Armstrong number:

A number is called as Armstrong number if the sum of cubes of each digit is equal to the number itself.
For example:

C program to find given number is armstrong or not

Output:

 
 
 

C program to find given number is armstrong or not using loop

Output:

Explanation:

We take a input number 153 from user and store it into variable num.
We copy the value of num into orgnum so that we will do calculation on num and place orgnum as it is.
Now the while loop will execute up to num=0.
In first iteration:
153 != 0(true)
{
rem = num % 10; // rem = 153%10 = 3
num = num / 10; // num = 153/10 = 15
sum = sum+(rem*rem*rem);// sum = 0+(3*3*3) = 27
}
Second iteration
15 != 0(true)
{
rem = num % 10; // rem = 15%10 = 5
num = num / 10; // num = 15/10 = 1
sum = sum+(rem*rem*rem);// sum = 27+(5*5*5) = 27 + 125 = 152
}
Third iteration
1 != 0(true)
{
rem = num % 10; // rem = 1%10 = 1
num = num / 10; // num = 1/10 = 0
sum = sum+(rem*rem*rem);// sum = 152+(1*1*1) = 152 +1 = 153
}
Forth iteration
0 != 0(false)

These are the iterations of while loop, now the value of the sum is compared with the value of orgnum.
if sum == orgnum then it is Armstrong number and if not then it is not Armstrong number.
In our case, input number is Armstrong number.

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.