Search code examples
cfactorial

Why doesn't this factorial compute correctly?


I am trying to learn some C programming, and to test my basic skills, I am making a simple program that computes factorials. However, instead of giving the correct answer of 120 for the factorial of 5, it gives -1899959296. What's wrong? Here's my code below:

#include <stdio.h>

int factorial(int x)
{
    int i;
    for(i=1; i < x; i++)
        x *= i;
    return x;
}

int main() 
{ 
    int a = 5, b;
    b = factorial(a);
    printf("The factorial of %d is %d \n", a, b);
    return 0;
}

Thanks in advance!


Solution

  • Your problem is that the function factorial() is continually modifying x. For any of x which is initially 3 or more, x will keep increasing, so the loop will keep running.

    Consider if you call fact(3).

    The function is called with x = 3. First iteration of the loop with i = 1 will multiply x by 1. So x will still have the value of 3. i i will be incremented to 2, which is less than 3, so the next iteration starts.

    The second iteration of the loop will multiply x by 2, giving the result of 6. i is incremented to 3, which is less than 6, so the next iteration starts.

    The third iteration will multiply x by 3, giving the result of 18. i is incremented to 4, which is less than 18, so the next iteration starts.

    Notice the pattern in the above ..... the end condition is i < x. i is incremented in each iteration. x is multiplied by i. This means that x increases substantially faster than i does .... which means i < x is always true.

    Well almost ..... eventually the logic breaks down.

    Eventually x will overflow - the result of multiplying it by i will produce a result that exceeds what can be stored in an int. The result of overflowing an int is undefined ..... anything can happen at that point.

    Compare the description above with what YOU would do if asked to compute the factorial of 3. Would you do similar steps? Probably not.