C Program to check a number is Armstrong or Not.

If you are learning c language and trying out all the basic programs related to it. You will see the Armstrong number program in every book. It is a very important program from the placement and exam point of view.
If you know nothing about the C language. I will suggest you check this link first. Introduction to C Language.
Before getting directly to the code. let’s first understand what is an Armstrong number.
Armstrong Number-
Armstrong is a number whose sum of cube of every digit is equal to the number of itself.
Example of Armstrong number – 153 is an Armstrong number because of the cube of 1, 5, 3 and sum gives 153 numbers.
I hope to know you will be able to understand easily.
Method 1 – Armstrong Number Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> #include<conio.h> int main() { int num, originalNum, remainder, result = 0; printf("Enter a three-digit integer: "); scanf("%d", &num); originalNum = num; while (originalNum != 0) { remainder = originalNum % 10; result += remainder * remainder * remainder; originalNum /= 10; } if (result == num) printf("%d is an Armstrong number.", num); else printf("%d is not an Armstrong number.", num); return 0; } |
Output – Enter a three-digit integer: 154 154 is not an Armstrong number.
In the above program, we have taken the number from the user and using the loop has taken the digits and cubing them and adding to the result variable.
Method 2 – Armstrong Number –
In the second method, we will use functions to perform the task when they are called.
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 |
#include <stdio.h> int armstrong(int ); int main() { int num, originalNum, ; printf("Enter a three-digit integer: "); scanf("%d", &num); originalNum = num; result= armstrong(num); if (result == num) printf("%d is an Armstrong number.", num); else printf("%d is not an Armstrong number.", num); return 0; } int armstrong(int ) { int remainder, result = 0; while (a!= 0) { remainder = a% 10; result += remainder * remainder * remainder; a/= 10; } return result; } |
The output will be the same as in the above method.
In this method, we created a function named Armstrong and calculated the sum of the cube of digits in it.
After calculating the result, it is returned back to the main program and after that, the comparison is made and results are fetched.
Try the same program using a five-digit number Example – 35422 and comment down the answer you got.
Recommended Posts –
- Introduction to C language
- Structure of C program
- C Program to add two numbers
- C Program to reverse a number
- Difference between C and C ++.
For more details can check the website: Armstrong Number