I'm having a hard time understanding this.

Hi, I'm a beginner in C++ and I'm having a hard time understand this code from the tutorial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// factorial calculator
#include <iostream>
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return (1);
}

int main ()
{
  long number;
  cout << "Please type a number: ";
  cin >> number;
  cout << number << "! = " << factorial (number);
  return 0;
}


When they explained it I still didnt get it. Even after reading it like a thousand times. Please help me.
the function is recursive. so lets use the example of factorial(3):

the first if statement is true and thus we get:
3*factorial(2)

again the first if statement is true:

3*2*factorial(1)

now the if statement is false so we get:

3*2*1

which is 3!


googling recursion and recursive functions should help.
I'm not going to attempt to explain it, because ultimately I think you have to explain it to yourself. However, I do suggest adding some output statements to display which part of the code is executed and what the values are. For example like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
long factorial (long a)
{
    cout << "a = " << a << endl;
    if (a > 1)
    {
        long temp = factorial (a-1);
        cout <<  a << " * " << temp << endl;
        return a * temp;
    }
    else
    {
        cout << " done " << endl;
        return (1);
    }
}

Input 5.
Output:
1
2
3
4
5
6
7
8
9
10
11
12
Please type a number: 5
a = 5
a = 4
a = 3
a = 2
a = 1
 done
2 * 1
3 * 2
4 * 6
5 * 24
5! = 120

Now the task is to understand the output. Left as an exercise for the reader...
Did I mention I DONT GET ENGLISH SO WELL?
@Program Programmer
Did I mention I DONT GET ENGLISH SO WELL?


I think that in this case you could ask your question in some national forum on programming.
Topic archived. No new replies allowed.