a function that calls it self

Hey guys , I just made a function that calls it self to return a a power , ex: 2,3 = 2*2*2 = 8
1
2
3
4
5
6
7
int power (int x,int y){
	if (y==0){
		return 1;
	}
	else {
	return x*	power (x,y-1);
	}


but

in here :

return x* power (x,y-1);

how does it work exactly ?

if i put 2 as x and 3 as y

it became :

2*power(2,3-1) ?

but please explain how does it work.

Keep expanding power(a,b) until you satisfy your base case to break the recursion (i.e. the second argument is 0):

power (2,3)  becomes
2 * power (2, 2)  becomes
2 * 2 * power (2,1)  becomes
2 * 2 * 2 * power (2,0)  becomes
2 * 2 * 2 * 1  (why 1? because we've hit our base case, where the second arg is 0)

put a breakpoint on line 6, and step into it. it's probably the best way to understand recursive functions.
thanks guys , you helped a lot ^^
Topic archived. No new replies allowed.