Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program for Armstrong Numbers
An Armstrong number (also known as narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 1 + 125 + 27 = 153.
Syntax
int armstrong(int number);
Formula
For an n-digit number with digits d?, d?, ..., d? ?
Armstrong Number = d?? + d?? + ... + d??
Example
This program checks if a given number is an Armstrong number using helper functions to calculate power and count digits ?
#include <stdio.h>
int power(int a, int b) {
int result = 1;
while (b > 0) {
result *= a;
b--;
}
return result;
}
int countDigits(int n) {
int count = 0;
while (n != 0) {
count++;
n = n / 10;
}
return count;
}
int armstrong(int n) {
int original = n;
int digits = countDigits(n);
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += power(digit, digits);
n /= 10;
}
return sum;
}
int main() {
int number = 1634;
if (number == armstrong(number)) {
printf("%d is an Armstrong number<br>", number);
} else {
printf("%d is not an Armstrong number<br>", number);
}
// Test with more examples
int testNumbers[] = {153, 371, 9474, 123};
int size = sizeof(testNumbers) / sizeof(testNumbers[0]);
printf("\nTesting other numbers:<br>");
for (int i = 0; i < size; i++) {
if (testNumbers[i] == armstrong(testNumbers[i])) {
printf("%d is an Armstrong number<br>", testNumbers[i]);
} else {
printf("%d is not an Armstrong number<br>", testNumbers[i]);
}
}
return 0;
}
1634 is an Armstrong number Testing other numbers: 153 is an Armstrong number 371 is an Armstrong number 9474 is an Armstrong number 123 is not an Armstrong number
How It Works
- countDigits() ? Counts the total number of digits in the given number
- power() ? Calculates the power of a digit raised to the number of digits
- armstrong() ? Extracts each digit, raises it to the power of total digits, and sums them up
- main() ? Compares the original number with the calculated sum
Common Armstrong Numbers
| Number | Digits | Calculation |
|---|---|---|
| 153 | 3 | 1³ + 5³ + 3³ = 153 |
| 371 | 3 | 3³ + 7³ + 1³ = 371 |
| 1634 | 4 | 1? + 6? + 3? + 4? = 1634 |
Conclusion
Armstrong numbers are special mathematical numbers where the sum of digits raised to the power of digit count equals the original number. This C program efficiently checks Armstrong numbers using modular functions for better code organization.
Advertisements
