Search code examples
cfactorial

When x became 40, y should be 0 right? How did the output became 1 in the 4th iteration, when y = 0?


#include <stdio.h>
int main()
{
    int num = 40585;
    int output = 0;

    for (int x = num; x > 0; x /=10)
    {
        int temp = 1;
        int y = x % 10;

        for (int i = y; i > 1; i--)
            temp *= i;

        output += temp;
    }

    if (output == num)
        printf("True");
    else
        printf("False");
} 

I thought when i became 0, the statement in the inner for loop would not run so output would be 0. When added all, I thought the result was 40584.


Solution

  • When x is 40, y is set to 0, and no iterations of the loop on i are executed.

    This leaves temp unchanged. temp was initialized to 1, so it remains 1, and output += temp adds 1 to output.

    This matches the mathematical definition of the factorial of 0, as 0! = 1.