WAP to print Armstrong numbers from 1 to n in C. Armstrong numbers also known as Narcissistic numbers are fascinating figures in mathematics and computer science. In this article, we will write a c program that prints all Armstrong numbers in the range of 1 to n. Where n is the user-defined limit.
How to Print Armstrong Numbers in range 1 to n
Writing the program Let’s outline the steps to find Armstrong numbers within the range 1 to n.
- Decide the value of n(Here we will take input from the user), The range we want to find the Armstrong number.
- For each number in this range calculate the sum of its digits raised to the power of the number of digits in the number.
- Compare the sum with the original number, if they are the same the number is an Armstrong number.
- Prints the number if it meets the criteria of an Armstrong number.
C Program to Print Armstrong Number from 1 to n
Let’s write the C program.
#include <stdio.h>
#include <math.h>
void main()
{
int n;
printf("Enter the value of n ");
scanf("%d", &n);
printf("\nAll Armstrong Number in Rang 1 to %d are -\n", n);
for (int i = 1; i <= n; i++)
{
int num = i;
int sum = 0;
int digits = (int)log10(num) + 1;
while (num > 0)
{
int digit = num % 10;
sum = sum + pow(digit, digits);
num = num / 10;
}
if (sum == i)
{
printf("%d ", i);
}
}
}
Output
The above C program takes the input of n from the user. After that, the for loop is used to iterate all numbers within the given range from 1 to n. Inside this loop, each number is checked if it is an Armstrong number. If the number is the Armstrong number then the program prints the number.
Happy Coding & Learning
2 thoughts on “WAP to print Armstrong numbers from 1 to n in C”