C Program to check a given number is armstrong or not
Objective
Write a C program to check if a given number is an Armstrong number.
Algorithm / Approach
- Read an integer
n. - First Pass (Count Digits): Use a loop to divide a temporary copy of
nby 10 until it hits 0, counting how many digits it has. - Second Pass (Calculate Sum): Use another loop on a fresh copy of
n. - Extract the last digit using
% 10. - Raise that digit to the power of the total digit count and add it to a sum:
sum = sum + pow(rem, digits). - If the final
sum == n, it is an Armstrong number.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
int n, sum =0, temp, rem, digits = 0;
printf("Enter a number : ");
scanf("%d",&n);
temp = n;
while(temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while(temp != 0) {
rem = temp%10;
int power = pow(rem, digits);
sum = sum + power;
temp = temp/10;
}
if(n == sum) {
printf("%d is an armstrong number");
}
else {
printf("%d is not an armstrong no.");
}
return 0;
}
Expected Output
Enter a number : 371 371 is an armstrong number
Explanation of the Program
- An Armstrong number (or Narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
- For example, 371 is a 3-digit number. If you calculate 33 + 73 + 13 (27 + 343 + 1), it perfectly equals 371.
Complexity
Time Complexity
O(log₁₀ n) - Two passes over the digits of the number.
Space Complexity
O(1)