This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

check Armstrong number in the C program

#include<stdio.h>
#include<math.h>
#define pow
int main()
{
    int num,num1,num2,n,q,sum=0,no_of_digits=0;
    printf("enter  a number\n");
    scanf("%d",&num);
    num1=num2=num; //storing the entered number in another variable 'num1'
    while (num!=0) //calclating and storing the number of digits in 'digit'
    {
        num=num/10; //dividing the number by 10. int data type ignores the decimal value, giving an integer
        no_of_digits++; 
    }
    while (num1!=0) 
    {
        n=num1%10; //taking one digit at a time in n
        q=pow(n,no_of_digits);//each digit^no. of digits
        sum=sum+q; // sum of all digit^no. of digits
        num1=num1/10;
        
    }
     printf("Sum of each digit^no. of digits =%d\n",sum);
     if (sum==num2)
        printf("%d is an armstrong number\n",num2);
     else
        printf("%d is NOT an armstrong number\n",num2);

  return 0;
} 

MY result: Sum of each digit^no. of digits =9 370 isn't an armstrong number 

Likewise, if i don't add the #define pow line,i get the following error. /usr/bin/ld: /tmp/ccGBiCYH.o: in function main': 7.c:(.text+0xda): undefined reference to pow' collect2: error: ld returned 1 exit status. 

Before trying this code I Read several Articles on the web on Armstrong number in C to understand the concept in a better way, Here, is the article I've read from Wikipedia, Scaler and Quora.

  • I'm guessing you either need to find a library that has pow in it, or write your own pow function.

  • In general, you don't want to use the "pow" function for integer powers, especially of other integers, since it does floating point and can introduce rounding errors.  Writing your own function that loops multiplication should be much better.

    With your "#define pow" statment, your current code produces "q = (n, no_of_digits);", which is a legal C statements ("comma operator"), but doesn't come anywhere near doing what you want.