C++ Program to find Armstrong numbers between two intervals

amstrong number between given range

Program to find Armstrong numbers between two intervals

Armstrong number is the number in which the sum of cubes of the individual digits of the number equals to the number itself.

To check for Armstrong number first break the number into digits, find and add the cubes of the individual digits, Compare the result with the number itself. If equal then the number is an Armstrong Number else not an Armstrong number.

For example:153 = 1 + 125 +27= 153.

In this program we will check for all the numbers in the range specified by the user.

Algorithm:-

  • Take  two inputs(one for lower limit & other for upper limit).
  • The inputs are stored in two int type variables say l_limit, u_limit.
  • Start a loop that will run from lowerLimit till upperLimit with every increment equal to 1
    • For every number in the range Call a function armstrong().
    • The function will tell whether a number is armstrong or not.
      • Cube of individual digits of the number is found
      • The cube is added.
      • If the sum is equal to the number itself then the number is an armstrong number.
      • Otherwise the number is not an armstrong number.
  • All the armstrong numbers in the user specified range are printed.
armstrong or not

C++ Code

#include<iostream>
#include<math.h>
using namespace std;
void armstrong(int num)
{
    int sum=0;
    int store = num;
    //find sum of cubes of individual digits
    do
    {
        int digit = num % 10;
        sum = sum + pow(digit,3);
        num = num / 10;
    }while(num > 0);
        //checking for ArmStrong number
    if(sum == store)    
            cout << store <<"\t";  
    }
int main()
{
    int l_limit,u_limit;
    cout<<"Enter the range:\n";
    cin>>l_limit>>u_limit;
    cout<<"Armstrong numbers between "<<l_limit<<" and " <<u_limit<<" are:\n";
    for(int i=l_limit;i<=u_limit;i++)
        armstrong(i);
    return 0;
}

Output

Enter the range:
1
999
Armstrong numbers between 1 and 999 are:
1	153	370	371	407