Search code examples
cloopsfor-loopfactorial

Why wont my factorial program result in the right answers?


I am attempting to write a C program that can calculate the factorial of a number inputted by a user. I have the program below, and it seems to work fine without any errors. However, everything I input a number like 5, I get a strange answer like -1899959296.

I cant seem to find where the error is, let alone how the answer is negative. Any help would be appreciated, thank you very much.

int main()
{
    int inputnumber;
    int n;
    
    printf("\nThis program is a factorial calculator. Input a number below to finds its factorial: ");
    scanf("%i", &inputnumber);
    
    //A 'for' loop repeats the same contained statements until a condition is met.
    //A general form of a 'for' statements is shown below:
    
    // for( initial values; loop condition; loop expression)
    
    for (n = 1; n <= inputnumber; n++)
    {
        inputnumber = inputnumber * n;
    }
    
    printf("\nThe answer is %i", inputnumber);

    return 0;
}

I attempted to make a factorial program, but all inputted numbers give very wrong answers.


Solution

  • The problem is this part of your code:

    for (n = 1; n <= inputnumber; n++)
    {
        inputnumber = inputnumber * n;
    }
    

    The code inside the loop increases inputnumber when n > 1. This causes the loop to run much longer than intended because n <= inputnumber (your loop conditional) is always satisfied until there is an integer overflow, i.e., when inputnumber < 0. Hence, the loop only stops when inputnumber becomes negative.

    To fix this, you should store your factorial result as a separate variable, e.g.:

    int result = 1;

    Then update your loop to be result *= n; (and obviously change your print statement accordingly).