please i need to learn this

i have a question how does this line work out
//(base * recursive(base, total -1);//
im confuse because you have 2 arguments first is base and second is total which is decremented by 1 everytime you make a recursive call, how does that work out do the arguments gets add or multiply to give a certain value to the recursive function? i dont know please

1
2
3
4
5
6
7
8
int recursive(int base,int total)
{
	if (total <= 1)
            return total;

	return (base * recursive(base, total -1);
	
}
Recursion is difficult to visualize. On top of that, it is not frequently useful. I don't know why it is taught so early in programming concepts.

Anyway... the easiest way to visualize this is to plug in some numbers.

Let's say you do:

 
cout << recursive(2,4);


What do you think this will output? Let's step through it.

base=2 and total=4. so recursive will return (base * recursive(base, total -1);... which, after plugging in our numbers will be:

 
return (2 * recursive(2,3));


recursive(2,3) will return (2 * recursive(2,2))
recursive(2,2) will return (2 * recursive(2,1))
and recursive(2,1) will return 1 because of the 'if' statement on line 3

So...

1
2
3
4
5
6
7
8
9
10
11
recursive(2,4)
=
2*recursive(2,3)
=
2*2*recursive(2,2)
=
2*2*2*recursive(2,1)
=
2*2*2*1
=
8


So cout << recursive(2,4) will output '8'.
thank you so much
Topic archived. No new replies allowed.