Checking for Armstrong numbers:

An Armstrong number is a number which is equal to the sum of digits raise to the total number of digits in that number.

Some examples of Armstrong numbers are:

7 = 71
371 = 33 + 73 + 13 (27 + 343 +1)

Checking if a number is an Armstrong number:

 
#include <stdio.h>

int  power(int  n, int  r) {

   int  c, p = 1;

   for  (c = 1; c & lt; = r; c++)

      p = p * n;

   return  p;

}

int  main()

{

   int  n, remainder;

   int  sum = 0;

   int  digits = 0;

   printf("Enter a number: ");

   scanf("%d", & amp; n);

   int  temp = n;

   while  (temp != 0) //counting the number of digits

   {

      digits++;

      temp = temp / 10;

   }

   temp = n;

   while  (temp != 0)

   {

      remainder = temp % 10;

      sum = sum + power(remainder, digits); //raising each digit to the number of digits and adding the result

      temp = temp / 10;

   }

   if  (n == sum)

      printf("%d is an Armstrong number.\n", n);

   else

      printf("%d isn't an Armstrong number.\n", n);

   return  0;

}

The output of the above program is:

 
Enter a number:  7

7 is an Armstrong number.
  • We first calculate the number of digits present in the number entered by the user.
  • After we have a count of the number of digits, we raise every digit to that count using the power function.

If the sum of the digits raise to the count of the digits is equal to the number entered by the user, then it is an Armstrong number, else it is not.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019