Printing All Armstrong/Narcissistic Numbers In an Interval In C++

Exercise:

Write a C++ program to print all Armstrong numbers present between an interval of two numbers.

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    long int num1, num2, ans, j, bit, sum=0;
    cout << "Enter the interval of two numbers:\n";
    cin >> num1 >> num2;
    cout << "Armstrong numbers between " << num1 << " and " << num2 <<    " are: " << endl;
    for(ans = num1; ans <= num2; ans++)
    {       
        sum=0;
        j = ans;         
    for(; j > 0; j /= 10)
    {
        bit = j % 10;
        sum += pow(bit,3);
    }
    if(sum == ans)
    {
        cout << ans << " ";
    }
}
return 0;
}
Click Here to View the Output:
Enter the interval of two numbers:
0
500
Armstrong numbers between 0 and 500 are:
0 1 153 370 371 407
Click Here to View the Explanation:
  • User is requested to enter two numbers.
  • The code enters for loop and divides by 10, saving the remainder.
  • The allows the number to be reversed. The user is expected to enter the smaller number first. In case the larger number is entered before the smaller number, code for swapping number can be added to the code.
  • The variables are inserted by the user and stored as num1 and num2 variables.
  • Then each digit of the entered number is taken and storied in bit. Exponent of 3 is added to bit with the pow() function.
  • After the digit is cubed, it is added to sum. sum is the answer of the cube of the last digit.
  • sum is compared to the originally entered number by the user ans. The output is given accordingly.

%d bloggers like this: