C program to check a number is Armstrong number or not; Through this tutorial, we will learn how to check the number is armstrong number in c program using if else and function.
Algorithm and Programs to check the Number is Armstrong Number or Not in C
Let’s use the following algorithm and program to check if a given number is armstrong number or not in c:
- Algorithm to check for Armstrong number
- C program to check a number is Armstrong number or not
- C Program to check whether a number is Armstrong number or not using function
Algorithm to check for Armstrong number
- Take a number as input from user and store it in an integer variable.
- Find the cubic sum of digits of inputNumber, and store it in sum variable.
- Compare inputNumber and sum.
- If both are equal then input number is Armstrong number otherwise not an Armstrong number.
C program to check a number is Armstrong number or not
/*
* C Program to check whether a number is armstrong number or not
*/
#include <stdio.h>
int main(){
int number, sum = 0, lastDigit, temp;
printf("Enter a number : ");
scanf("%d", &number);
temp = number;
while(temp != 0){
lastDigit = temp%10;
sum = sum + (lastDigit*lastDigit*lastDigit);
temp = temp/10;
}
if(sum == number){
printf("%d is Armstrong Number \n", number);
} else {
printf("%d is not an Armstrong Number \n", number);
}
return 0;
}
The output of above c program; as follows:
Enter a number : 789 789 is not an Armstrong Number
C Program to check whether a number is Armstrong number or not using function
/*
* C Program to check whether a number is armstrong number or not
*/
#include <stdio.h>
int getCubicSumOfDigits(int number);
int main(){
int number, sum;
printf("Enter a number ");
scanf("%d", &number);
sum = getCubicSumOfDigits(number);
if(sum == number){
printf("%d is Armstrong Number \n", number);
} else {
printf("%d is not an Armstrong Number \n", number);
}
return 0;
}
/*
* Funtion to calculate the sum of cubes of digits of a number
* getCubicSumOfDigits(123) = 1*1*1 + 2*2*2 + 3*3*3;
*/
int getCubicSumOfDigits(int number){
int lastDigit, sum = 0;
while(number != 0){
lastDigit = number%10;
sum = sum + lastDigit*lastDigit*lastDigit;
number = number/10;
}
return sum;
}
The output of above c program; as follows:
Enter a number 153 153 is Armstrong Number