Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Monday 2 January 2017

Armstrong Number C Code

Armstrong number is a number that is equal to the sum of the digits raised to the power of the number of digits. So for example:

371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371


There are other such numbers as well: 150, 370, 407, 8208, 1741725, etc.


According to Wikipedia Narcissistic Number or Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits. This definition depends on the base b of the number system used, e.g., b = 10 for the decimal system or b = 2 for the binary system.




C Code to check Armstrong Number:

/* Double-Click To Select Code */
#include <stdio.h>
#include <conio.h> 
int power(int, int);
 
void main()
{
   int n, sum = 0, temp, remainder, digits = 0;
 
   printf("Input an integer\n");
   scanf("%d", &n);
 
   temp = n;
   // Count number of digits
   while (temp != 0) {
      digits++;
      temp = temp/10;
   }
 
   temp = n;
 
   while (temp != 0) {
      remainder = temp%10;
      sum = sum + power(remainder, digits);
      temp = temp/10;
   }
 
   if (n == sum)
      printf("%d is an Armstrong number.\n", n);
   else
      printf("%d is not an Armstrong number.\n", n);
}
 
int power(int n, int r) {
   int c, p = 1;
 
   for (c = 1; c <= r; c++) 
      p = p*n;
 
   return p;   
}

Output:

Armstrong Number C Code

Please share if this post helped you :)


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: