### I'm having trouble understanding recursive functions?

closed account (3UMLy60M)
Hello all,

Can someone please explain to me how calling m3(3, 4) causes 81 to be the output of the following recursive function?

 ``1234567`` ``````int m3 (int a, int b) { if (b == 0) return 1; else return a * m3(a, b - 1); }``````

And also, why is the output here 12 when m2(3, 4) is called?

 ``1234567`` ``````int m2(int a, int b) { if (a == 0) return 0; else return b + m2(a - 1, b); }``````

Thanks!
m3(3, 4) will return 3 * m3(3, 3),
m3(3, 3) will return 3 * m3(3, 2),
m3(3, 2) will return 3 * m3(3, 1),
m3(3, 1) will return 3 * m3(3, 0) and
m3(3, 0) will return 1,
so in other words m3(3, 4) will return 3 * (3 * (3 * (3 * 1))) = 81.

analyze your own code ;)

m3 (3,4) = 3 * (3,3) = 3 * 3 * (3,2) = 3 * 3 * 3 * (3,1) = 3 * 3 * 3 * 3 * (3,0) = 3 * 3 * 3* 3 * 1 = 81

m2(3,4) = 4 + (2,4) = 4 + 4+ (1,4) = 4 + 4 + 4 + (0,4) = 4 + 4 + 4 + 0 = 12
Last edited on
Why are you duplicating your post in two section of the forum? Do not do that.
Topic archived. No new replies allowed.