Armstrong number in C

Viewed 78

I can't figure out why it's always output nothing; can someone help me?

#include<stdio.h>
#include<stdlib.h>

int main() {

  int i, num, sum;

  for (i = 100; i < 1000; i++)
  {
      sum = 0;
      for (num = i; num != 0; num /= 10)
      {
        sum += (i % 10) ^ 3;
      }
      if (sum == i)
        printf("%d ", i);
  }
  system("pause");
  return 0;
}
1 Answers

The ^ operator is not exponentiation in C – rather, it is the bitwise XOR (exclusive OR) operator.

To raise a number to a given power, you'll need to call the pow function (but that works with floating-point numbers); alternatively, when the power is 3, just perform two consecutive multiplications.

Also, in your code, you should be using num % 10 (not i % 10) in the inner for loop:

#include<stdio.h>
#include<stdlib.h>

int main()
{

    int i, num, sum;

    for (i = 100; i < 1000; i++) {
        sum = 0;
        for (num = i; num != 0; num /= 10) {
            int digit = num % 10;
            sum += digit * digit * digit;
        }
        if (sum == i)
            printf("%d ", i);
    }
    system("pause");
    return 0;
}
Related