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:
1 |
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number. |
C program to find given number is armstrong or not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<stdio.h> int main() { int num, n, sum, rem1, rem2, rem3; printf("Enter 3 digit number\n"); scanf("%3d", &n); num = n; rem1 = n % 10; n = n/10; rem2 = n % 10; n = n/10; rem3 = n % 10; n = n/10; sum = rem1*rem1*rem1 + rem2*rem2*rem2 + rem3*rem3*rem3; if(num == sum) { printf("it's armstrong no."); } else printf("it's not armstrong no."); return 0; } |
Output:
1 2 3 |
Enter 3 digit number 603 it's not armstrong no. |
1 2 3 |
Enter the number 153 it's armstrong no. |
C program to find given number is armstrong or not using loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> int main() { int num, orgnum, sum=0, rem; printf("Enter the number\n"); scanf("%d", &num); orgnum = num; while(num != 0) { rem = num % 10; num = num / 10; sum = sum + (rem * rem * rem); } if(sum == orgnum) { printf("%d is armstrong number", orgnum); } else printf("%d is not armstrong number", orgnum); return 0; } |
Output:
1 2 3 |
Enter the number 153 153 is not armstrong number. |
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.