C++ Program to Display Armstrong Number Between Two Intervals


An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number.

Some examples of Armstrong numbers are as follows −

3 = 3^1
153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407
1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

A program that displays the Armstrong numbers between two intervals is as follows.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum ;
   lowerbound = 100;
   upperbound = 500;
   cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
   for(int num = lowerbound; num <= upperbound; num++) {
      temp = num;
      digitNum = 0;
      while (temp != 0) {
         digitNum++;
         temp = temp/10;
      }
      temp = num;
      digitSum = 0;
      while (temp != 0) {
         remainderNum = temp%10;
         digitSum = digitSum + pow(remainderNum, digitNum);
         temp = temp/10;
      }
      if (num == digitSum)
      cout<<num<<" ";
   }
   return 0;
}

Output

Armstrong Numbers between 100 and 500 are: 153 370 371 407

In the above program, Armstrong numbers between the given intervals are found. This is done using multiple steps. The lowerbound and upperbound of the interval are given. Using these, a for loop is started from lowerbound to upperbound and each number is evaluated to see if it is an Armstrong number or not.

This can be seen in the following code snippet.

lowerbound = 100;
upperbound = 500;
cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
for(int num = lowerbound; num <= upperbound; num++)

In the for loop, first the number of digits in the number i.e in num are found. This is done by adding one to digitNum for each digit.

This is demonstrated by the following code snippet.

temp = num;
digitNum = 0;
while (temp != 0) {
   digitNum++;
   temp = temp/10;
}

After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits.

This can be seen in the following code snippet.

temp = num;
digitSum = 0;
while (temp != 0) {
   remainderNum = temp%10;
   digitSum = digitSum + pow(remainderNum, digitNum);
   temp = temp/10;
}

If the number is equal to the digitSum, then that number is an Armstrong number and it is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet.

if (num == digitSum)
cout<<num<<" ";

Updated on: 24-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements