Reputation: 140
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
Reputation: 95
Upvotes: 0
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