Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

Recursion in c++ Factorial Program

hello i have this piece of code that i coded based on some other recursion and factorial programs but my problem is that i am really confused as to how it stored the value and kept it and then returned it at the end

int factorialfinder(int x)
{
    if (x == 1)
    {
        return 1;
    }else
    {
        return x*factorialfinder(x-1);
    }
}
int main()
{
  cout << factorialfinder(5) << endl;
}

so 5 goes in, and gets multiplied by 4 by calling its function again and again and again, then it gets to one and it returns the factorial answer

why? i have no idea how it got stored, why is return 1 returning the actual answer, what is it really doing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...