C++ Program to Display Armstrong Number Between Two Intervals

Here is a C++ program to print all armstrong numbers between two intervals. In this C++ program, we will find all armstrong numbers between two given integers. Here is a brief introduction of armstrong number:

An Armstrong number is a number whose sum of cubes of every digit of a number is equal to the number itself.
For Example:
407 is an Armstrong number
407 = 4*4*4 + 0*0*0 + 7*7*7

Algorithm to check for Armstrong Number
  • Take a number as input from user and store it in an integer variable(Let's call it inputNumber).
  • Find the cubic sum of digits of inputNumber, and store it in sum variable.
  • Compare inputNumber and sum.
  • If both are equal then input number is Armstrong number otherwise not an Armstrong number.

In this program, we will take two two integers as input from user and then print all armstrong numbers between given two integers. Here is the C++ program to print all armstrong number between given interval.


C++ program to print all armstrong numbers between two integers

#include <iostream>
using namespace std;
 
int getCubicSumOfDigits(int number){
    int lastDigit, sum = 0;
    while(number != 0){
        lastDigit = number%10;
        sum = sum + lastDigit*lastDigit*lastDigit;
        number = number/10;
    }
    return sum;
}

int main(){
    int x, y, sum, i;
    
    cout << "Enter two integers\n";
    cin >> x >> y;
    
 cout << "Armstrong numbers between " << x <<" and "<< y << endl;
    for(i = x; i <= y; i++){
        sum = getCubicSumOfDigits(i);
        if(sum == i){
            cout << i << endl;
        }
    }

    return 0;
}
Output
Enter two integers
200 500
Armstrong numbers between 200 to 500
370
371
407

In above program, we first take two numbers as input from user and store it in variable x and y. Using a for loop, we iterate from x till y and check for each number whether it is armstrong number or not.
We have defined a function "getCubicSumOfDigits", which takes an integer parameter as input and then returns the sum of cubes of digits of a number. Inside getCubicSumOfDigits function, we extract digits of number one by one add the cube of the digit to a variable sum.

For Example:
getCubicSumOfDigits(123) = 1*1*1 + 2*2*2 + 3*3*3 = 36.

Finally, we compare the cubic sum of digits of a number with the number itself. If both are equal than number is an armstromg number otherwise not an armstromg number.


Recommended Posts
C++ Program to Print All Prime Numbers Between 1 to N
C++ Program to Check for Armstrong Number
C++ Program to check Whether a Number is Palindrome or Not
C++ Program to Find Power of Number using Recursion
C++ Program to Delete Spaces from String or Sentence
C++ Program to Delete Vowels Characters from String
C++ Program to Store Information of an Employee in Structure
C++ Program to Find Area and Circumference of a Circle
C++ Program to Print Floyd Triangle
All C++ Programs