An Armstrong number (also known as a narcissistic number or pluperfect digit) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, the number 153 is an Armstrong number because:
Logic of the Armstrong Number Program:
- Input a number from the user.
- Determine the number of digits in the number.
- Calculate the sum of each digit raised to the power of the total number of digits.
- Check if this sum is equal to the original number.
- Print whether the number is an Armstrong number or not.
Program:
Here’s a C program to check if a number is an Armstrong number:
Explanation:
Variables:
int num
: Holds the number inputted by the user.int originalNum
: Used to store the original number for comparison later.int remainder
: Stores the current digit being processed.int count
: Counts the number of digits in the number.int result
: Stores the sum of the digits raised to the power of the number of digits.
Input:
- The program prompts the user to enter an integer.
Counting Digits:
- The program counts the number of digits by continuously dividing
originalNum
by 10 until it reaches zero.
- The program counts the number of digits by continuously dividing
Calculating the Armstrong Sum:
- The program resets
originalNum
to the input number. - It then calculates the sum of each digit raised to the power of the total number of digits.
- The program resets
Comparison:
- Finally, the program checks if the calculated sum (
result
) is equal to the original number (num
).
- Finally, the program checks if the calculated sum (
Output:
- The program prints whether the number is an Armstrong number or not based on the evaluation.
Sample Output:
Example 1:
Example 2:
Example 3:
Key Points:
- Power Calculation: The program uses the
pow
function from themath.h
library to calculate the power of the digits. - Digit Extraction: The program effectively extracts digits by using the modulus and division operations.
- User Interaction: The program interacts with the user, making it easy to input different numbers for testing.
- Flexibility: The program can check for any integer, making it versatile for testing various cases.