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 math library
- C Data Types
- C functions
- C
main()
function - C
for
loop statement - C
while
loop statement - C
if
condition statement - C
printf()
function
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 <stdio.h>
#include <math.h>
// @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;
}
printf("\nArmstrong numbers between %d and %d is: ", low_number, high_number);
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) {
printf("%d ", i);
}
// last it will reset the values of count & result
count = 0;
result = 0;
}
printf("\n");
return 0;
}
// @driver function to call & find the armstrong numbers
int main() {
int low_number, high_number;
printf("Enter the two intervals:\n");
scanf("%d %d", &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
1000
Armstrong numbers between 100 and 1000 is: 153 370 371 407
Note: We used math.h
library to use the mathematical functions in this program.
Explanation
In this program, we have taken inputs 100
and 1000
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.