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
Check the number is Armstrong or not using C
An Armstrong number (also known as a narcissistic number) is a number that equals 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.
Syntax
number = sum of (each digit ^ number_of_digits)
Algorithm
To check if a number is an Armstrong number −
- Count the number of digits in the given number
- Calculate the sum of each digit raised to the power of total digits
- Compare this sum with the original number
Example 1: Basic Armstrong Number Check
This example checks if a given number is an Armstrong number using a simple approach −
#include <stdio.h>
#include <math.h>
int main() {
int number, temp, remainder, digits = 0, sum = 0;
printf("Enter a number: ");
scanf("%d", &number);
temp = number;
/* Count number of digits */
while (temp != 0) {
digits++;
temp /= 10;
}
temp = number;
/* Calculate sum of digits raised to power of total digits */
while (temp != 0) {
remainder = temp % 10;
sum += pow(remainder, digits);
temp /= 10;
}
if (number == sum) {
printf("%d is an Armstrong number<br>", number);
} else {
printf("%d is not an Armstrong number<br>", number);
}
return 0;
}
Enter a number: 153 153 is an Armstrong number
Example 2: Checking Multiple Armstrong Numbers
This example demonstrates checking different types of Armstrong numbers −
#include <stdio.h>
#include <math.h>
int isArmstrong(int num) {
int temp = num, digits = 0, sum = 0, remainder;
/* Count digits */
while (temp != 0) {
digits++;
temp /= 10;
}
temp = num;
/* Calculate sum */
while (temp != 0) {
remainder = temp % 10;
sum += pow(remainder, digits);
temp /= 10;
}
return (num == sum);
}
int main() {
int numbers[] = {153, 371, 1634, 8208, 123};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Checking Armstrong numbers:<br>");
for (int i = 0; i < size; i++) {
if (isArmstrong(numbers[i])) {
printf("%d is an Armstrong number<br>", numbers[i]);
} else {
printf("%d is not an Armstrong number<br>", numbers[i]);
}
}
return 0;
}
Checking Armstrong numbers: 153 is an Armstrong number 371 is an Armstrong number 1634 is an Armstrong number 8208 is an Armstrong number 123 is not an Armstrong number
Key Points
- 3-digit Armstrong numbers: 153, 371, 407
- 4-digit Armstrong numbers: 1634, 8208, 9474
- The power depends on the number of digits, not always 3
- Use
pow()function frommath.hfor accurate calculations
Conclusion
Armstrong number verification involves counting digits and calculating the sum of each digit raised to the power of total digits. This concept is useful for understanding number theory and digit manipulation in C programming.
Advertisements
