Search code examples
ceclipserecursionfactorial

Recursive factorial program in C hangs when executing


I'm writing a program to display the time needed to calculate a factorial of a given number 2 million times. I'm writing it using Debian Linux in the C/C++ Eclipse environment. When the program gets to int temp = n * rfact(n-1);, it hangs and won't do anything else.

Here's what I've got so far:

#include <stdio.h>
#include <time.h>

//prototypes
int rfact(int n);

main()
{
    int n = 0;
    int i = 0;
    double result = 0.0;
    clock_t t;
    printf("Enter a value for n: ");
    scanf("%i", &n);

printf("n=%i\n", n);

    //get current time
    t = clock();

    //process factorial 2 million times
    for(i=0; i<2000000; i++)
    {
        rfact(n);
    }

    printf("n=%i\n", n);

    //get total time spent in the loop
    result = (clock() - t)/(double)CLOCKS_PER_SEC;

    //print result
    printf("runtime=%d\n", result);
}

//factorial calculation
int rfact(int n)
{
    int temp = n * rfact(n-1);
    printf(i++);
    return temp;
}

Solution

  • You are missing the base case, so you are running into an infinite recursion. You need to stop when you get to n == 1 or n == 0:

    int rfact(int n)
    {
        if (n <= 0)
            return 1;
        return n * rfact(n-1);
    }
    

    Also, the factorial function is not really the best use case for recursion because the iterative version is arguably more readable and possibly a lot faster, but that's a different story :)