-4

Why does my code work correctly only when 12>=a ??

int main()
{
    int a ,x = 1;
    scanf("%d", &a);
    
    while (1 < a){
        x = a * x;
        a = (a - 1);
        printf("\n %d", x);
    };

    printf("\n %d", x);
    return 0;
}

what i did is asking the pc to print the result of a*(a-1) in every line then it prints the final factorial result. And yes , the result is correct but not in all cases (from 13 and above it becomes wrong)

ssd
  • 2,340
  • 5
  • 19
  • 37
  • Probably, 13! is too big to fit to `int`. – user31264 Nov 08 '21 at 07:30
  • Overflow! BTW, signed overflow is UB. – Sourav Ghosh Nov 08 '21 at 07:31
  • The numerical limits of the various integer types are typically addressed in the first chapters of any beginner-level C book. I'd advise to do an utter minimum of research by reading those introductory chapters before asking questions on SO. – Lundin Nov 08 '21 at 07:34

1 Answers1

0

It is because factorial of 13 is greater than the holding capacity of int. So it cannot hold this value. try to use long variable here

Satyam Shankar
  • 250
  • 2
  • 12
  • On most systems, `long` is 4 bytes long, just like `int`. So, better make it `int64_t` (that is, `long long int`). – ssd Nov 08 '21 at 07:37