C++ Program to Display Armstrong Number Between Two Intervals

81
views
Program to Display Armstrong Number

Program to find and Display Armstrong Number between two integers (entered by the user) using loops and if…else statement in C Programming.

To understand this example to find and Display Armstrong Number, you should have the knowledge of following C++ programming topics:

  • C++ if, if…else and Nested if…else
  • C++ for Loop

This program asks a 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 a little complex.

Program to 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.

[irp]

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

You can add the code to swap two numbers entered by the user if the 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, the sum is compared with the original number i. If they are equal, the number is an Armstrong number.

Ask your questions and clarify your/others doubts on C++ Program to Display Armstrong Number Between Two Intervals by commenting. Documentation