English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to find all Armstrong numbers between the two integers entered by the user.
To understand this example, you should understand the followingC ProgrammingTopic:
A positive integer is called an Armstrong number (n-th order) if
abcd... = an + bn + cn + dn +
For3digit Armstrong number, the sum of the nth power of each digit equals the number itself. For example,153is an Armstrong number because
153 = 1*1*1 + 5*5*5 + 3*3*3
Before trying this program, please learn how toCheck if the integer is an Armstrong number.
#include <math.h> #include <stdio.h> int main() { int low, high, number, originalNumber, rem, count = 0; double result = 0.0; printf("Enter two numbers (interval): "); scanf("%d %d", &low, &high); printf("%d and %d between Armstrong numbers are: ", low, high); //Convert the number from(low + 1)Iterate to(high - 1) //In each iteration, check if the number is an Armstrong for (number = low + 1; number < high; ++number) { originalNumber = number; //Digit calculation while (originalNumber != 0) { originalNumber /= 10; ++count; } originalNumber = number; //The result includes the sum of the nth powers of the individual digits while (originalNumber != 0) { rem = originalNumber % 10; result += pow(rem, count); originalNumber /= 10; } //Check if the number is equal to the sum of the nth power of each digit if ((int)result == number) { printf("%d ", number); } //Reset values count = 0; result = 0; } return 0; }
Output result
Enter two numbers (interval): 200 2000 200 and2Armstrong numbers between 000 and: 370 371 407 1634
In the program, the outer loop starts from(low + 1)Iterate to(high-1)In each iteration, it checks whether the number is an Armstrong number.
Inside the outer loop, first calculate the number of digits of an integer and store it in count. And, the sum of the powers of each digit is stored in the result variable.
If the number is equal to result, then the number is an Armstrong number.
Note:You need to reset count and result to 0 in each iteration of the outer loop.