ForWebTech
ForWebTech

Reputation: 140

try to make a factorial program in C

Fortunately this program works fine to find the factorials of 1 to 12 but after 12 as 13, 14, 20 ..... output getting wrong and i also try to find the factorial of 40 and the output was 0. Failed to find the exact problem...

#include <stdio.h>

int main() {

   int user_input, tbl;

   printf("Enter any number: \t");
   scanf("%i", &user_input);

   tbl = user_input; 

   for(int i=2; i < user_input; i++) {
      tbl = tbl * i;
   }

    printf("Factorial of %i is %i", user_input, tbl);

}

Upvotes: 2

Views: 879

Answers (2)

liuyip
liuyip

Reputation: 95

  • 8bit unsigned char Max:0xFF-->255 ->2^8 - 1 (char)2^7 -1
  • 16bit unsigned short Max:0xFFFF -->2^16 - 1(short)2^15 - 1
  • 32bit unsigned int Max:0xFFFFFFFF -->2^32 - 1(int)2^31 - 1
  • 64bit unsigned.....Max:... --> 2^64 - 1(long long)2^63 - 1
  • All have Range.This is not the number written on the paper.

Upvotes: 0

Johannes Weiss
Johannes Weiss

Reputation: 54071

You're getting an integer overflow. On most machines, int is 32 bit wide (and obviously signed). That means the biggest number it can represent is 2^31-1 which is 2147483648. 12! works as it's 479001600 (which is smaller than 2^31-1) but 13! is 6227020800. So 13! can't usually be represented in an int.

One option you have is to make i, user_input and tbl a bigger type for example a unsigned long long or a uint64_t (from #include <inttypes.h>). But these types will also have a maximum representable number.

If you actually need arbitrary precision in C, you might want to consider GMP (The GNU Multiple Precision Arithmetic Library).

Also please be aware that overflows of signed types have undefined behaviour in C.

Upvotes: 8

Related Questions