I cant understand this code!!

I download the tutorial in this site.I got a proplems in understanding this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> // factorial calculator
using namespace std;
int add (int a) // proplems start here
{
    if (a>1)
    return a*add (a-1); //this is the big proplem
    else return 1;
} // end here
int main ()
{
int x;
cin >> x;
cout << add (x);
return 0;
}

i want someone to tell me how this code work.
please answer my question fast
Last edited on
What do you want to know? It takes input from the user on line 12 and passes it to the add(...) function on line 13. From here the code executes Line 3 through Line 8. Do you have a specific question?
Last edited on
i mean in return a*add (a-1);
for ex
the user entered 5 the value return is 120 how???why???
i think it should return the value 20 <<5*4=20>>
Last edited on
For 5, the function returns this:

5*add(5-1) = 5*add(4)

For 4, this function returns:
4*add(3)
3: 3*add(2)
2: 2*add(1)
1: 1

So 5 returns:

5*add(4) = 5*4*add(3) = 5*4*3*add(2) = 5*4*3*2*add(1) = 5*4*3*2*1 = 120
Please take time to study this. I hope it helps. Try visualize smalls numbers like 1, 2 and 3 first.
add(5) = 5*add(4)
           add(4) = 4*add(3)
                      add(3)= 3*add(2)
                                add(2) = 2*add(1)
                                           =1
                                2      = 2*1
                      6     = 3*2
           24     = 4*6
120    = 5*24
[edit]
Too slow..
Last edited on
thanx.
but why stop in 1??
why it dosnt complete to 0 then -1
if its because (if) it should return 1 because
1
2
if (a>1).....
else return 1; 
Last edited on
It is returning 1. It's just then being multiplied by all the previous numbers you had been returning. blackcoder's chart can help you see that.
Topic archived. No new replies allowed.