C++ program to display armstrong number between two intervals using user defined function
In this article, you will learn how to find the Armstrong numbers between two intervals in the c++ programming language.
You should have knowledge of the following topics in c++ programming to understand this program:
- C++
cmath
library - C++ Data Types
- C++ functions
- C++
main()
function - C++
for
loop statement - C++
while
loop statement - C++
if
condition statement - C++
cout
object - C++
cin
object
Armstrong Number
A positive integer is called an Armstrong number (of order n) if
Examples
Source Code
// C++ program to display armstrong number between two intervals using user defined function
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
// @custom function to find the armstrong numbers
int findArmstrongNumbers(int low_number, int high_number) {
int original_number, remind, count = 0, temp;
double result = 0.0;
// this will swap the value of intervals between each other
// if low_number is greater then high_number
if (low_number > high_number) {
temp;
temp = low_number;
low_number = high_number;
high_number = temp;
}
cout << "\nArmstrong numbers between " << low_number << " and " << high_number << " is: ";
for (int i = low_number + 1; i < high_number; i++) {
original_number = i;
// first it will count digits of numbers
while (original_number != 0) {
original_number = original_number/10;
count++;
}
original_number = i;
// second it will contains sum of nth power of individual digits
while (original_number != 0) {
remind = original_number % 10;
result += pow(remind, count);
original_number = original_number/10;
}
// third it will check if number is equal to the sum of nth power of individual digits
if ((int)result == i) {
cout << i << " ";
}
// last it will reset the values of count & result
count = 0;
result = 0;
}
cout << "\n";
return 0;
}
// @driver function to call & find the armstrong numbers
int main() {
int low_number, high_number;
cout << "Enter the two intervals:\n";
cin >> low_number >> high_number;
// @call the custom function to find the armstrong numbers
findArmstrongNumbers(low_number, high_number);
return 0;
}
Output
Enter the two intervals:
100
2000
Armstrong numbers between 100 and 2000 is: 153 370 371 407 1634
Note: We used cmath
library to use the mathematical functions in this program.
Explanation
In this program, we have taken inputs 100
and 2000
from the user then these pass to findArmstrongNumbers()
function as arguments.
Then this function make the calculation to find the Armstrong numbers between these intervals
behind this program, we used the pow()
function from the math library to calculate the exponents of digits' numbers.