An Armstrong number, also known as a 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, 153 is an Armstrong number because:
1³ + 5³ + 3³ = 153
In C programming, checking if a number is an Armstrong number involves three key steps:
- Extracting the digits: We need to get each digit of the number.
- Calculating the sum of the digits raised to the power of the number of digits.
- Comparing the sum with the original number.
Let’s look at an example of how to implement this in C.
C Program to Check Armstrong Number:
#include <stdio.h>
#include <math.h>
int main() {
int num, sum = 0, temp, remainder, digits = 0;
// Input the number
printf("Enter an integer: ");
scanf("%d", &num);
// Store the number in a temporary variable
temp = num;
// Count the number of digits in the number
while (temp != 0) {
temp /= 10;
++digits;
}
temp = num;
// Calculate the sum of the powers of the digits
while (temp != 0) {
remainder = temp % 10;
sum += pow(remainder, digits); // Raise the digit to the power of number of digits
temp /= 10;
}
// Check if the sum equals the original number
if (sum == num)
printf("%d is an Armstrong number.\n", num);
else
printf("%d is not an Armstrong number.\n", num);
return 0;
}
How the Program Works:
- Input: The program first takes an integer input from the user.
- Digit Counting: It calculates the number of digits in the number.
- Armstrong Check: It then calculates the sum of the digits raised to the power of the number of digits and compares it to the original number.
Conclusion:
The Armstrong number check is a great example of how we can manipulate digits and use mathematical functions in C. It helps reinforce the concepts of loops, conditional statements, and mathematical functions in programming.