Armstrong Number in C: What Is Armstrong Number in C & Code
Programming in C to verify an armstrong number is a mix of digit counting, exponentiation of integer, and loop accumulating. To understand what is armstrong number in c, an armstrong number in c is a positive integer with n digits where an Armstrong (or narcissistic) number if the sum of the n-th powers of its digits is equal to the number, e.g., 153 = 1^3 + 5^3 + 3^3 or 9474 = 9^4 + 4^4 + 7^4 + 4^4 etc. Always use a helper loop to calculate integer powers in c check armstrong number, not floating-point pow(), as rounding errors with IEEE-754 can result in numbers such as 5^3 becoming 124.999999, which will truncate to 124 on casting back to int.
### Armstrong Number in C: Exact Integer Power Check & Loop Trace
Programming in C to verify an armstrong number is a mix of digit counting, exponentiation of integer, and loop accumulating. To understand what is armstrong number in c, an armstrong number in c is a positive integer with n digits where an Armstrong (or narcissistic) number if the sum of the n-th powers of its digits is equal to the number, e.g., 153 = 1^3 + 5^3 + 3^3 or 9474 = 9^4 + 4^4 + 7^4 + 4^4 etc. Always use a helper loop to calculate integer powers in c check armstrong number, not floating-point pow(), as rounding errors with IEEE-754 can result in numbers such as 5^3 becoming 124.999999, which will truncate to 124 on casting back to int.
Interactive Runnable C Implementation
#include <stdio.h>
static int int_pow(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; ++i) result *= base;
return result;
}
int is_armstrong(int n) {
if (n < 0) return 0;
int temp = n, digits = 0;
do { ++digits; temp /= 10; } while (temp > 0);
temp = n;
int sum = 0;
while (temp > 0) {
sum += int_pow(temp % 10, digits);
temp /= 10;
}
return sum == n;
}
int main(void) {
int candidates[] = {153, 370, 9474, 123};
for (size_t i = 0; i < 4; ++i) {
int val = candidates[i];
printf("%d -> %s\n", val, is_armstrong(val) ? "Armstrong" : "Not Armstrong");
}
return 0;
}
Expected Output
153 -> Armstrong
370 -> Armstrong
9474 -> Armstrong
123 -> Not Armstrong