C++ Program to Display Armstrong Number Between Two Intervals

Example to find all Armstrong numbers between two integers (entered by the user) using loops and if...else statement.

To understand this example, you should have the knowledge of following C++ programming topics:

This program asks user to enter two integers and displays all Armstrong numbers between the given interval.

If you don't know how to check whether a number is Armstrong or not in programming then, this program may seem little complex.

Visit this page to learn about Armstrong number and how to check it in C++ programming.

Example: Display Armstrong Number Between Intervals

#include <iostream>
using namespace std;

int main()
{
  int num1, num2, i, num, digit, sum;

  cout << "Enter first number: ";
  cin >> num1;

  cout << "Enter second number: ";
  cin >> num2;

  cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " << endl;
  for(i = num1; i <= num2; i++)
  {
        sum = 0;
        num = i;

        for(; num > 0; num /= 10)
        {
            digit = num % 10;
            sum = sum + digit * digit * digit;
        }

        if(sum == i)
        {
            cout << i << endl;
        }
  }

  return 0;
}

Output

Enter first number: 100
Enter second number: 400
Armstrong numbers between 100 and 400 are:
153
370
371

In this program, it is assumed that, the user always enters smaller number first.

This program will not perform the task intended if user enters larger number first.

You can add the code to swap two numbers entered by user if user enters larger number first to make this program work properly.

In this program, each number between the interval is taken and stored in variable num. Then, each digit of the number is retrieved in digit and cubed (^3).

The cubed result is added to the cubed result of the last digit sum.

Finally, when each digit is traversed, sum is compared with the original number i. If they are equal, the number is an armstrong number.