Check if a number is an Armstrong number or not in C++
hello everyone,
In this tutorial, we learn about How to check if a number is an Armstrong number or not, with the help of c++.
before we start, let’s know about what is Armstrong number or how can we say that this is an Armstrong number?
Armstrong number is a number if the sum of the cubes of its digits is equal to the number itself.
let’s see an example:
153 = 1 *1 *1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
So, 153 is an Armstrong number, because the result is equal to the number itself.
lets see another example also,
371 = 3*3*3 + 7*7*7 + 1*1*1
= 27 + 343 + 1
= 371
How to check if a number is an Armstrong number or not in C++
let’s see the code snippet:
#include<iostream>
using namespace std;
int main ()
{
int num, temp, rem, sum = 0;
cout << "Enter a number: ";
cin >> num;
temp = num;
while (temp != 0)
{
rem = temp % 10;
sum = sum + rem*rem*rem;
temp = temp / 10;
}
if (sum == num)
cout << " It is an Armstrong number.";
else
cout
<< " It is not an Armstrong number.";
return 0;
}
in the above piece of code, iostream is used for input /output stream, int main() tells the compiler that function will return an integer value.
A number which is entered by the user is stored in the variable num, we store num into temp for using later in the program,
while (temp != 0)
- it is used to find the number of digits in a given number.
if (sum == num)
- it is used to check whether the sum is equal to the number or not.
rem = temp % 10;
- rem stores every individual digit of that number which is entered by the user
temp = temp / 10;
- Every time temp divided by 10 and the outcome will store in temp if temp becomes zero the loop will be ended.
output: Enter a number: 371 It is an Armstrong number.
Do let me know in the comments section if you have any doubts.
Also read:
Leave a Reply