In this guide, we will write a C program to print all Armstrong numbers between the given ranges.
A number is called Armstrong number, if it satisfies the following condition:
abc...n = an + bn+ cn+... Here, n is the number of digits in the number
For example:
2 is an Armstrong number because 2 = 21
12 is not an Armstrong number because 12 != 12 + 22
370 is an Armstrong number because 370 = 33 + 73 + 03
C Program
Steps in the following program:
- Get the lower range and higher range values from the user using scanf.
- If the user enters higher range first and lower range second then swap the ranges so that the program works as expected.
- Check each number in the given range and print the number if it is an Armstrong number.
#include <math.h> #include <stdio.h> int main() { int lowRange, highRange, number, checkNumber, rem, count = 0; double result = 0.0; printf("Enter the lower range and upper range: "); scanf("%d %d", &lowRange, &highRange); printf("Armstrong numbers from %d to %d are: ", lowRange, highRange); // if higher range is lower than lower range then swap those ranges if (highRange < lowRange) { highRange += lowRange; lowRange = highRange - lowRange; highRange -= lowRange; } // Check each number between lowerRange and highRange for (number = lowRange; number <= highRange; number++) { checkNumber = number; // Counting number of digits in the checkNumber while (checkNumber != 0) { checkNumber /= 10; ++count; } //restoring the value of checkNumber after counting digits checkNumber = number; // calculate sum of nth power of individual digits // and store the result in the variable result while (checkNumber != 0) { rem = checkNumber % 10; result += pow(rem, count); checkNumber /= 10; } // check if number is equal to result, if it is then //the number is an Armstrong number so print that number if ((int)result == number) { printf("%d ", number); } // resetting the values for the next number in the range count = 0; result = 0; } return 0; }
Output: Armstrong numbers between 1 and 1000