Printing Armstrong Numbers using While Loops in C
This is a C program that prompts the user to enter two integers, 'i' and 'n', and then uses a while loop to find and print all the Armstrong numbers between 'i' and 'n' (inclusive). An Armstrong number is a number that is equal to the sum of the cubes of its digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
- The #include<stdio.h> is a preprocessor directive that includes the contents of the standard input-output library in the program. The int main() function is the starting point of the program execution. Inside the main function, several integers are declared. printf() is used to display the prompts for the user to enter the starting and ending values, and scanf() is used to get the input and store it in the variables 'i' and 'n' respectively.
- A while loop is used to execute the code inside the loop as long as the condition i<=n is true. The first time the code is executed, the current value of 'i' is divided by 10 and the remainder is stored in variable 'b' using b=i%10. Then the quotient obtained is again divided by 10 and the remainder is stored in variable 'd' using d=a%10 and the quotient is stored in variable 'c' using c=a/10.
- Then the cubes of b,c,d are calculated and stored in variables b,c,d respectively.Then the sum of b,c,d is stored in variable 'e' using e=b+c+d. Then the condition i==e is checked, if it's true the current value of 'i' is printed using printf("\n%d",i) and the variable 'arms' is incremented by 1. Then the value of 'i' is incremented by 1. Then the condition i<=n is checked, if it's true the control jumps back to the start of the loop and the same process is repeated until the condition is false.
- Finally, the program prints the total number of Armstrong values using printf("\nTotal number of armstrong values:%d",arms) and returns 0 to indicate the successful execution of the program.
Source Code
#include<stdio.h>
int main()
{
int i,n,h,arms=0,a,b,c,d,e;
printf("\nEnter the starting value:");
scanf("%d",&i);
printf("\nEnter the Ending value:");
scanf("%d",&n);
printf("\nArmstrong numbers:");
while(i<=n)
{
a=i/10;//12
b=i%10;//8
c=a/10;//1
d=a%10;//2
b=b*b*b;
c=c*c*c;
d=d*d*d;
e=b+c+d;
if(i==e)
{
printf("\n%d",i);
arms++;
}
i++;
}
printf("\nTotal number of armstrong values:%d",arms);
return 0;
}
To download raw file
Click Here
Output
Enter the starting value:100
Enter the Ending value:999
Armstrong numbers:
153
370
371
407