Complementary task for topic: 4
M Nemeth · 2023-08-29 15:21:04.618220'
Functions: Check Armstrong Number
Functions: Check Armstrong Number
Write a C function is_armstrong that takes an integer as input and returns 1 if the number is an Armstrong number, and 0 otherwise. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Hint:
Solution
#include
#include
// Function to check if a number is an Armstrong number
int is_armstrong(int num) {
int original = num, n = 0, sum = 0;
while (num != 0) {
num /= 10;
++n;
}
num = original;
while (num != 0) {
int digit = num % 10;
sum += pow(digit, n);
num /= 10;
}
return (original == sum);
}
int main() {
int num;
printf("Enter a number to check if it is an Armstrong number: ");
scanf("%d", &num);
if (is_armstrong(num))
printf("%d is an Armstrong number.\n", num);
else
printf("%d is not an Armstrong number.\n", num);
return 0;
}
Explanation
The is_armstrong function takes an integer num as input and checks if it is an Armstrong number. To do this, it first calculates the number of digits in num by counting how many times num can be divided by 10 until it becomes 0. Then, it calculates the sum of each digit raised to the power of the number of digits (n) using the pow function from the math.h library. Finally, the function compares the calculated sum with the original number. If they are the same, the number is an Armstrong number.