- 2071 Chaitra · 4 marks
Armstrong numbers in a range
Short answer
The program defines an is_armstrong function that counts digits, computes the sum of each digit raised to that power, and returns 1 if it equals n. main reads lower/upper limits, loops through the range, calls the function, and prints Armstrong numbers along with their count. For 1–1000, output: 1 2 3 4 5 6 7 8 9 153 370 371 407, count=13.
Write a program to display Armstrong numbers between the range entered by a user and also display their counts. You must use a function to check for Armstrong numbers and display them from main.
The function is_armstrong(n) counts the digits of n, adds each digit raised to that power, and returns 1 if the sum equals n. main() reads the limits, loops through the range, calls the function, prints the Armstrong numbers and counts them.
#include <stdio.h>
int is_armstrong(int n)
{
int t = n, digits = 0, sum = 0, d, p, i;
while (t > 0) { digits++; t /= 10; }
t = n;
while (t > 0)
{
d = t % 10;
p = 1;
for (i = 0; i < digits; i++)
p *= d;
sum += p;
t /= 10;
}
return sum == n;
}
int main(void)
{
int lo, hi, i, count = 0;
printf("Enter lower and upper limits: ");
scanf("%d %d", &lo, &hi);
printf("Armstrong numbers: ");
for (i = lo; i <= hi; i++)
if (is_armstrong(i))
{
printf("%d ", i);
count++;
}
printf("\nCount = %d\n", count);
return 0;
}
Output for the range 1 to 1000:
Enter lower and upper limits: Armstrong numbers: 1 2 3 4 5 6 7 8 9 153 370 371 407
Count = 13
The Armstrong numbers between 1 and 1000 are 1 to 9, 153, 370, 371 and 407 (13 in total).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function definition; sum of two numbers · Computer Programming, chapter 6
- nth Fibonacci term prime check · Computer Programming, chapter 6
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Switch versus user defined function · Computer Programming, chapter 5
- Algorithm for numbers divisible by 9 not 6 · Computer Programming, chapter 2
- Pass student array; display passed students · Computer Programming, chapter 7
- 8086 ALP: vowels to uppercase, counts · Microprocessor, chapter 3
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- 8086 ALP: largest and smallest, display · Microprocessor, chapter 3