Algorithm
1. Start
2. Read the lower and upper limits of the interval (lower_limit, upper_limit)
3. For each number i in the interval [lower_limit, upper_limit]:
a. Set sum = 0
b. Set temp = i
c. While temp is not 0:
i. Extract the last digit (digit) from temp
ii. Add digit^3 to sum
iii. Divide temp by 10
d. If sum is equal to i, then i is an Armstrong number
e. Print i
4. End
Code Examples
#1 Code Example- C++ Program Display Armstrong Number Between Intervals
Code -
C++ Programming
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num1, num2, i, num, digit, sum, count;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
// swap if num1 > num2
if (num1 > num2) {
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " <<endl;
// print Armstrong numbers from num1 to num2
for(i = num1; i <= num2; i++) {
// count gives the number of digits in i
count = 0;
// store value of i in num
num = i;
// count the number of digits in num and i
while(num > 0) {
++count;
num /= 10;
}
// initialize sum to 0
sum = 0;
// store i in num again
num = i;
// get sum of power of all digits of i
while(num > 0) {
digit = num % 10;
sum = sum + pow(digit, count);
num /= 10;
}
// if sum is equal to i, then it is Armstrong
if(sum == i) {
cout << i << ", ";
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Output
Enter second number: 10000
Armstrong numbers between 1 and 10000 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474,
#2 Step 1: Find the Number of Digits in i
Code -
C++ Programming
count = 0;
num = i;
// count the number of digits in num and i
while(num > 0) {
++count;
num /= 10;
}
Copy The Code &
Try With Live Editor
#3 Step 2: Find the Sum of Powers of Each Digit
Code -
C++ Programming
while(num > 0) {
digit = num % 10;
sum = sum + pow(digit, count);
num /= 10;
}
Copy The Code &
Try With Live Editor
#4 Step 3: Check if sum is Equal to i
Code -
C++ Programming
if(sum == i) {
cout >> i >> ", ";
}
Copy The Code &
Try With Live Editor
Demonstration
C++ Programing Example to Display Armstrong Number Between Two Intervals-DevsEnv