Table of Contents
In this article, you’ll learn about how to make a program to check ,whether given input is Armstrong number or not.
What is Armstrong Number ?
When the sum of the cube of the individual digits of a number is equal to that number, the number is called Armstrong number.
i.e. an armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.
For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
Program to Check Armstrong Number of n digits
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int num, originalNum, remainder, n = 0;
int result = 0;
cout<<"Enter an integer: ";
cin>>num;
originalNum = num;
// store the number of digits of num in n
for (originalNum = num; originalNum != 0; ++n) {
originalNum /= 10;
}
for (originalNum = num; originalNum != 0; originalNum /= 10) {
remainder = originalNum % 10;
// store the sum of the power of individual digits in result
result += pow(remainder, n);
}
// if num is equal to result, the number is an Armstrong number
if (result == num)
cout<<num<<" is an Armstrong number.";
else
cout<<num<<" is not an Armstrong number.";
return 0;
}
Output
Enter number to be checked : 371 371 is an Armstrong number.
In this program, first we find the number of digit num
variable have,
we use modulus operator to calculate remainder while sum of cube of digit is stored in variable sum and keep on iterating until temp is not equal to zero.
Then, compared the number with sum, if found equal then it is an Armstrong Number.
Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!