0

I just learned about Recursive functions and they seem very confusing to me, and hard to trace the logic, sometimes i end up staring at it pretty much time to understand the logic, so i can write it.
So, i was wondering if there are some simplified steps i could follow to make it a little bit easier to write them and to see the logic, instead of just jumping in the function and trying to figure it out.

Thanks in Advance

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by rubberman
0

I found it helpful when I was learning recursive behavior to write the function out at each step with indentation. For instance, given the following:

int fun (int n) {
   if (n < 1) return 1;
   else return 1 + fun (n - 1);
}

I would write it out like:

fun(3)
-- if (3 < 1) [fail]
-- return 1 + fun (2)
fun (2)
-- -- if (2 < 1) [fail]
-- -- return 1 + fun (1)
fun (1)
-- -- -- if (1 < 1) [fail]
-- -- -- return 1 + fun (0)
fun (0)
-- -- -- -- if (0 < 1) return 1
-- -- -- -- return 1
-- -- -- 1 + 1 (result of fun (0))
-- -- 1 + 2 (result of fun (1))
-- 1 + 3 (result of fun (2))
4 (result of fun (3))

Often times paper and pencil are your best approach.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.