Program to Find Armstrong Numbers in a Given Range in C
Armstrong Number in a Given Range
An Armstrong number (or narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 and 9474 are Armstrong numbers.
We will explore a method to find Armstrong numbers within a given range using C programming.
Method: Using a for Loop
We iterate through the given range and check each number for the Armstrong condition.
#include <stdio.h> #include <math.h> int isArmstrong(int num) { int originalNum = num, sum = 0, digit, n = 0; // Count the number of digits while (originalNum != 0) { originalNum /= 10; n++; } originalNum = num; // Calculate the sum of digits raised to the power of n while (originalNum != 0) { digit = originalNum % 10; sum += pow(digit, n); originalNum /= 10; } return (sum == num); } int main() { int start, end; printf("Enter the range (start end): "); scanf("%d %d", &start, &end); printf("Armstrong numbers between %d and %d are: ", start, end); for (int i = start; i <= end; i++) { if (isArmstrong(i)) { printf("%d ", i); } } return 0; }
Output:
Enter the range (start end): 1 1000 Armstrong numbers between 1 and 1000 are: 1 153 370 371 407