ADVERTISEMENT
Armstrong Between 1 and Given Input
This program calculates the sum of the cubes of the digits for each number within the given range and checks if the sum is equal to the original number. If this condition is met, the number is considered an Armstrong number, and it’s printed.
#include<stdio.h>
#include<math.h>
main()
{
int num,i,j,temp1,temp2,sum=0;;
printf("Enter a number to know all armstrong number between them\n");
scanf("%d",&num);
printf("Armstrong numbers are:\n");
for(i=1;i<=num;i++)
{
sum=0;
temp1=i;
temp2=i;
while(temp1>0)
{
j=temp1%10;
sum+=pow(j,3);
temp1=temp1/10;
}
if(sum==temp2)
{
printf("%d\n",sum);
}
}
}
C Programming ExamplesEnter a number to know all armstrong number between them
5000
Armstrong numbers are:
1
153
370
371
407C Programming ExamplesExplanation:
This C program is designed to find all Armstrong numbers within a given range. An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits. Let’s go through the code step by step:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
User Input:
The program begins by prompting the user to enter a number (num), which is considered as the upper limit of the range for searching Armstrong numbers.
Initialization:
Several variables are declared and initialized:
- temp1 and temp2: These variables are used to store the original number (as it’s being processed), so they are both initialized with the value of the current number in the loop (i).
- sum: It’s used to calculate the sum of the cubes of individual digits of a number, and it’s initialized to 0.
Loop to Find Armstrong Numbers:
The program enters a for loop that iterates from 1 to the specified upper limit (num).
Inside the loop:
- sum is initialized to 0 for the current number (i).
- The digit extraction process begins. The while loop is used to extract each digit from the number (temp1) and calculate the sum of its cubes.
- Inside the while loop:
- j is used to extract the last digit of temp1 (i.e., j = temp1 % 10).
- The cube of j is added to the sum.
- The last digit is removed from temp1 by dividing it by 10 (i.e., temp1 = temp1 / 10).
- After processing all digits, if the sum is equal to the original number (temp2), it means that the current number is an Armstrong number.
- If the condition is true, the program prints the Armstrong number.
Printing Armstrong Numbers:
The program prints all the Armstrong numbers found within the specified range.