C++ Program to find Armstrong numbers between two intervals

Program to find Armstrong numbers between two intervals

Here we will discuss how to find the Armstrong numbers in between the range specified by the user using the C++ Programming language.

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

Sum of cubes of digits   = 13 + 53 +33

                = 153.

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

Armstrong numbers between two intervals

Working

Let’s see how the code works:

  • User gives 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.

C++ Code

//C++ Program
//Armstrong number in a interval
#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

Please Login/Signup to comment