Search code examples
cfactorial

Unable to get a factorial function to work in C


I cannot get the following code to work.

#include <stdio.h>

// I am not sure whethere I should void here or not.
int main() {
    // when the first bug is solved, I put here arg[0]. It should be
    // similar command line parameter as args[0] in Java.
    int a=3;                  
    int b; 
    b = factorial(a);

    // bug seems to be here, since the %1i seems to work only in fprintf
    printf("%1i", b);
    return 0;      
}  

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

How can you get the code to work?


Solution

  • AInitak gave the right answer, but I want to add that one way you can find the bug in your code is to print out the values of i and x in the factorial loop.

    int factorial(int x) {
        int i;
        for(i=1; i<x; i++)
        {
            x *= i;
            printf("%d, %d\n", i, x);
        }
        return x;
    }
    

    This gives you the output

    1, 3
    2, 6
    3, 18
    4, 72
    5, 360
    6, 2160
    7, 15120
    8, 120960
    9, 1088640
    10, 10886400
    11, 119750400
    12, 1437004800
    13, 1501193216
    14, -458131456
    -458131456
    

    This makes it easier to see what's going wrong. The loop doesn't stop where you expect it to for the reasons AInitak explained.