Recursion in c++ Factorial Program

Recursion image from IBM developers website.

Source: Image is taken from: IBM Developers website

Just take a look at the picture above, you will understand it better. The number never gets stored, but gets called recursively to calculate the output.

So when you call the fact(4) the current stack is used to store every parameter as the recursive calls occur down to factorialfinder(1). So the calculation goes like this: 5*4*3*2*1.

int factorialfinder(int x)         
{
    if (x == 1)        // HERE 5 is not equal to 1 so goes to else
    {
        return 1;
    }else
    {
        return x*factorialfinder(x-1); // returns 5*4*3*2*1  when x==1 it returns 1
    }
}

Hope this helps.

Leave a Comment