Search code examples
c++recursionstack-overflowcompiler-warningsfactorial

"Recursive on All Control Paths" error when implementing factorial function


For class I have an assignment:

Write a C++ program that will output the number of distinct ways in which you can pick k objects out of a set of n objects (both n and k should be positive integers). This number is given by the following formula:

C(n, k) = n!/(k! * (n - k)!)

Your program should use two value-returning functions. The first one should be called factorial and should return n!. The second function should be called combinations and should return n!/(k! * (n - k)!). Test your program for different values of n and k five times (count-controlled loop).

I came up with a solution:

#include <iostream>
using namespace std;
int factorial(int);
int combination(int, int);

void main(void)
{
    int objects, set_number, count; 
    count = 1; 
        while(count <= 5)
        {
            cout << "Please enter in number of objects ";
            cin >> objects; 
            cout << "Please enter in the number of Sets ";
            cin >> set_number;
            count++;
        }

    cout << "The Factorial is " << factorial(set_number) << " & the combination is " << combination << endl;
    cout << endl; 
}

// Factorial 
int factorial(int set_number)
{
    int cal;
    cal = set_number * factorial(set_number - 1);
    return cal; 
}

//  Combination
int combination(int objects, int set_number)
{
    int com_total, cal_set, cal_obj, min_sum, cal_min;

    cal_set = set_number * factorial(set_number - 1);
    cal_obj = objects * factorial(objects - 1);
    
    //n!/(k! * (n - k)!)
    min_sum = set_number - objects; 
    cal_min = min_sum * factorial(min_sum- 1);
    com_total = cal_set / (cal_obj * cal_min);
    return com_total; 
}

...but I keep getting an error, that says;

"'factorial' : recursive on all control paths, function will cause runtime stack overflow;"

If someone could help me, I've been working on this for about an hour and I'm stumped!


Solution

  • There are two critical elements to a recursive function definition:

    • a recursive call to itself
    • a termination condition

    You appear to be missing the termination condition. How would factorial() quit calling itself forever?