1

I am finding Armstrong number but it's showing "not a Armstrong number" Everytime and I can't find the solution. as my observation I think there is some problem the sum section. the sum is not giving the correct value.

#include<stdio.h>
#include<math.h>
int main()
{
    int num, original_num, sum=0, lastdigit, digit, count=1;

    printf("Enter the number: ");
    scanf("%d", &num);

    original_num = num;

    while (num >= 10)
    {
        count++;
        num /= 10;
    }
    digit = count;

    while (num > 0)
    {
        lastdigit = num % 10;
        sum += pow(lastdigit, digit);      /** here is the problem lying as my 
                                              observation, the sum is giving the 
                                              incorrect value.**/
        num/=10;
    }
    if (original_num == sum)
    {
        printf("The number is an ARMSTRONG number");
    }
    else
    {
        printf("The number is not a ARMSTRONG number");
    }
    return 0;
    }
ario
  • 15
  • 3
  • Don't use the floating-point `pow` function for integer powers. Better create your own function. – Some programmer dude Sep 20 '22 at 08:19
  • In your second loop you use `num`, is this correct, as it is smaller than 10 after the first loop? – the busybee Sep 20 '22 at 08:19
  • This also seems like a very good time to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs. For example by using a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. – Some programmer dude Sep 20 '22 at 08:20
  • thanks and yes i should now know about how to use debugger.. – ario Sep 20 '22 at 08:35
  • Thank you for this question. Never heard of these before (that I can remember.)... Just wrote my version of the code that found (below 1000) 4 Armstrong numbers! Cool... Thanks! `:-)` (Two of those numbers VERY interesting!) – Fe2O3 Sep 20 '22 at 08:55
  • @Fe2O3 can you please show me your code. i am having problem when i am trying with range instead of user input. and you are welcome. – ario Sep 20 '22 at 09:38
  • @Fe2O3 i already solved my question , i just want to see your code. and i can not see any code here – ario Sep 20 '22 at 11:38

1 Answers1

0

num has already became single digit after first while loop(which counts the number of digits). In which case your second loop which takes every digit in the number and raise it to the n power is running only once.

You need to restore the number before second loop.

  num = original_num; 

   while (num > 0)
    {
        lastdigit = num % 10;
        sum += pow(lastdigit, digit);      
        num/=10;
    }
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44