C++ Program to Display Armstrong Number Between Two Intervals

In this post, we will learn how to display Armstrong numbers between two intervals using C++ Programming language.

As we know, an Armstrong number is a number whose sum of cubes of every digit of a number is equal to the number itself.

Today, we will find and print all the armstrong numbers lying between two numbers with the help of if statement and for loop.

So, without further ado, let’s begin this tutorial. 

C++ Program to Display Armstrong Number Between Two Intervals

// C++ Program to Display Armstrong Number Between Two Intervals
#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int i, min, max, temp1, temp2, num = 0, rem, sum = 0;
    
    // Asking for input
    cout << "Enter the first number: ";
    cin >> min;
    cout << "Enter the last number: ";
    cin >> max;
    
    cout << "Armstrong numbers between " << min << " to " << max << " are: "<< endl;
    for (i = min; i < max; i++){
        temp1 = i;
        temp2 = i;
        
        while (temp1 != 0){
            temp1 = temp1 / 10;
            num++;
        }
        while (temp2 != 0){
            rem = temp2 % 10;
            sum = sum + pow(rem, num);
            temp2 = temp2 / 10;
        }
        
        // Checking for armstrong number
        if (sum == i){
            cout << i << endl;
        }
        num = 0;
        sum = 0;
    }
    return 0;
}

Output

Enter the first number: 10
Enter the last number: 1000
Armstrong numbers between 10 to 1000 are: 
153
370
371
407

How Does This Program Work ?

    int i, min, max, temp1, temp2, num = 0, rem, sum = 0;

In this program, we have declared eight integer data type variables.

    // Asking for input
    cout << "Enter the first number: ";
    cin >> min;
    cout << "Enter the last number: ";
    cin >> max;

The user is asked to enter the minimum and maximum number of the range.

        while (temp2 != 0){
            rem = temp2 % 10;
            sum = sum + pow(rem, num);
            temp2 = temp2 / 10;
        }

We calculate the sum of cubes of the digits of the number using a while loop.

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

If the sum of cubes of the digit is equal to the iteration, then that iteration is an Armstrong number and we print it on the screen.

Conclusion

I hope after going through this post, you understand how to display Armstrong numbers between two intervals using C++ Programming language.

If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to solve your doubts.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *