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

Recommended Answers

All 2 Replies

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.

Often times paper and pencil are your best approach.

Amen to that! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.