Recursion: I need help understanding.

In this c++ book im reading and in a c++ learning app im using. it tells me that to break the loop of a function that calls itself, use the "recursive function"code below. in the "Else" statement of the code below it uses:

return x * factorialfinder(x - 1)

why am I returning the multiplication of x by the function factorialfinder(x - 1)?

I used this return and got the same result:

return factorialfinder(x - 1)

my output in both of the different returns after entering 5 to be the factorial was:

Type in a factorial 5
Not yet
Not yet
Not yet
Not yet
Now
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;

int factorialfinder(int x){
    if(x == 1){
       cout << "Now";
       return 1;
}else{ cout << "Not yet" << endl;
      return x * factorialfinder(x - 1)}

int main(){

int send = 0;
cout << "type in a factorial: "
cin >> send;
factorialfinder(send);

getchar();
return 0;
Last edited on
I used this return and got the same result:

That's because you aren't printing the actual result that factorialfinder() returns. When I change line 16 to:
cout << '\n' << send << " factorial is " << factorialfinder(send) << '\n';
then the output is:
type in a factorial: 5
Not yet
Not yet
Not yet
Not yet
Now
5 factorial is 120

or
type in a factorial: 5
Not yet
Not yet
Not yet
Not yet
Now
5 factorial is 1

Depending on whether line 9 multiplies by x.
oh so they were teaching me how recursion can break out of a function call loop and how to factorial interger numbers at the same time.

Thanks.
If you do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int factorialfinder (int x)
{
    if (x==1)
    {
        std::cout << "Now.\n";
        return 1;
    }

    return x*factorialfinder(x-1);
}

int main()
{
    int n=0;

    std::cout << "Intro num.: ";
    std::cin >> n;

    std::cout << factorialfinder(n) << "\n";
    
    return 0;
}


then it works as expected.
Topic archived. No new replies allowed.