An Armstrong number which number, the actual number and reverse of that number both are equal. For example: 12521 is an Armstrong number.
// Write a c program to generate all armstrong number till n.
#include<stdio.h>
#include<stdbool.h>
int reverse(int n){
int reverse = 0;
while(n > 0){
int last_digit = n % 10; // get the last digit
reverse = reverse * 10 + last_digit; // last digit store in the reverse variable
n = n / 10; // Remove the last digit
}
return reverse;
}
bool isArmstrong(int n){
if(n == reverse(n)){
return true;
}
return false;
}
int main(){
int n;
printf("Enter the number upto which you want to generate the armstrong number : ");
scanf("%d", &n);
for(int i = 1; i <= n; i++){
if(isArmstrong(i)){
printf("%d ", i);
}
}
return 0;
}
#include<stdio.h>
stdio.h is a standard library which used to used the input/output operation.
#include<stdbool.h>
stdbool.h is a standard library which used to the boolean opeartion.
// Reverse function
int reverse(int n){
int reverse = 0;
while(n > 0){
int last_digit = n % 10; // get the last digit
reverse = reverse * 10 + last_digit; // last digit store in the reverse variable
n = n / 10; // Remove the last digit
}
return reverse;
}
The above reverse() function is used to reverse any number. In Details Read now.
// Check armstrong function isArmstrong()
bool isArmstrong(int n){
if(n == reverse(n)){
return true;
}
return false;
}
The above isArmstrong() functioon is check that given number is armstrong or not, this function return type is bool it returns only true or false. If the number is Armstrong then return true otherwise return false. In Details Read now.
// main function
int main(){
int n;
printf("Enter the number upto which you want to generate the armstrong number : ");
scanf("%d", &n);
for(int i = 1; i <= n; i++){
if(isArmstrong(i)){
printf("%d ", i);
}
}
return 0;
}
It is the main function, which known as the entry point of the program. Declared a variable as integer, Read the number which you want to generate the Armstrong number. Check all number from 1 o n iterate using for loop and check every number Armstrong or not using isArmstrong(i) function, if return true then print that number.
Comments
Oops!