Exercises:
Write a C++ program to check if the entered number is an Armstrong number.
Program 1: 3 Digit Number
Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int num, NUM, rem, ans = 0;
cout << "Insert a number: ";
cin >> num;
NUM = num;
while (NUM != 0)
{
// rem contains the last digit
rem = NUM % 10;
ans += pow(rem,3);
// remove last digit from the NUM
NUM /= 10;
}
if (ans == num)
cout << "It is an Armstrong number";
else
cout << "It is not an Armstrong number";
return 0;
}
Click Here to View the Output:
Insert a number:153 It is an Armstrong number
Click Here to View the Explanation:
- Last digit of the entered number is removed with
while
loop. It is iterated until the new value ofNUM
equals 0. - Through every iteration, the last digit of
NUM
is extracted, saved inrem
, and cubed and added toans
which is originally set equal to 0. The value ofans
is updated. - The last digit of
NUM
is then removed from it. - When
NUM
equals 0, the loop is terminated and the cubes of numbers are added. - It is checked if
ans == num
Program 2: For n Number of Digits.
Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int num, NUM, rem, pwr;
int n = 0, ans = 0;
cout << "Insert a number: ";
cin >> num;
NUM = num;
while (NUM != 0)
{
NUM /= 10;
++n;
}
NUM = num;
while (NUM != 0)
{
rem = NUM % 10;
pwr = round(pow(rem, n));
ans += pwr;
NUM /= 10;
}
if (ans == num)
cout << "It is an Armstrong number.";
else
cout << "It is not an Armstrong number.";
return 0;
}
Click Here to View the Output:
Insert a number: 9474 It is an Armstrong number.
Click Here to View the Explanation:
- For this program, the number of digits is calculated first and stored as a variable
n = 0
. - Then
while
loop is used withpow()
function to calculate the exponent of each number. ans
andnum
and compared using anif
statement. The output is printed on the screen accordingly.