In this C programming example, we will write a program to check Armstrong Number in C. We will start with Armstrong Number.
Before that, you should have knowledge of the following topics in C programming.
What is an Armstrong Number?
A number is said to be an Armstrong Number if even after the sum of its digits, where each digit is raised to the power of the number of digits is equal to the original number. For example 153, 371, 407, 9474, etc are Armstrong numbers.
C Program to Check for Armstrong Number
This program checks Armstrong number for 3 digit numbers only, not more than 3 digits.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<stdio.h> int main() { int num, temp, sum = 0, rem; //user input for number printf("Enter the number: "); scanf("%d",&num); /*storing it to another so that the original value could be used later*/ temp = num; //cubes of every digit while (num != 0) { rem = num % 10; sum = sum + (rem*rem*rem); num = num / 10; } //comaparing with original value if(temp == sum) printf("%d is an Armstrong Number", temp); else printf("%d is not an Armstrong Number", temp); return(0); } |
Output:
Enter the number: 371
371 is an Armstrong Number
C Program Check Armstrong Number of n number of digits
This number checks Armstrong Number for any number of digits. Armstrong Number finds the power of each digit to the number of digits present in that number such as:
Number: 1634
=1^4+6^4+3^4+4^4
=1+1296+81+256
=1634
The original Number and sum of the number are the same. Therefore, it is an Armstrong Number.
To make it simple, we have used one of the math functions, pow()
provided by math.h
library. The pow()
takes two-digit, one the number whose power needs to be found and the other is the power itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <math.h> #include <stdio.h> int main() { int num, temp, rem, n = 0, sum = 0; printf("Enter the Number: "); scanf("%d", &num); temp = num; //counting number of digits by increasing n for (temp = num; temp != 0; ++n) { temp /= 10; } temp = num; while (temp != 0) { rem = temp % 10; //adding and storing in sum variable sum += pow(rem, n); temp /= 10; } //comaparing with original value if (sum == num) printf("%d is an Armstrong number", num); else printf("%d is not an Armstrong number", num); return 0; } |
Output:
Enter the number: 1634
1634 is an Armstrong Number
The programs first stored the number of digits present in the number by incrementing the n
value so that it can be later used in calculating the power as shown in the program.