Search code examples
c++stack-overflow

why is it giving error stackoverflow back?


so i have been learning c++ for the past few days and now i have a task to make a Recursion and recursive function. i tried to solve it but it always gives this error back (Unhandled exception at 0x00535379 in cours.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00392FC4).) or sometimes it gives the value of 1 of sum any ideas for why?

int factorialNumber(int a,int b)
{
    int sum;
    if (b==a)
    {
        return b;
    }
        sum = a*b;
        return sum  + factorialNumber(b + 1,a);
}

void main(int sum)
{
    int a=8,b=1;
    factorialNumber(a,b);
    cout <<a <<b<<endl<<sum;
    system("pause>0");
}

Solution

  • There are few other error in you code from C++ perspective, like invalid syntax for main, missing header, etc. But ignoring them for now to concentrate on factorial thing. You main error order of passing a and b to factorialNumber. Correcting it like below will work.

    int factorialNumber(int a,int b)
    {
        int sum;
        if (b==a)
        {
            return b;
        }
            sum = a*b;
            return sum  + factorialNumber(a,b + 1);
    }