# Having trouble on logic behind recursion

I am struggling to write my own recursive function.I understand how to find the base case but I cant find easily the pattern on the relationship between 2 complicated cases.Do you know any website where I can practice that?

• It is your choice to keep the mystery about "2 complicated cases". That strongly limits the extent to which we might be of help.
– user16034
Aug 30, 2023 at 12:41
• Do you know about proof by induction? Aug 30, 2023 at 13:11

The philosophy behind recursion is to decompose the problem in subproblem(s) of the same nature but easier in some respect, until the subproblems are so simple that you can solve them easily.

For instance, to sort an array, you can move the small elements on the first side and the large ones on the last side and sort the two sides separately. You trade a large problem for two easier ones (because the number of elements are smaller). When this number is tiny, you can sort by a straightforward method (in particular, sorting a single element is immediate).

The whole story is about reducing the problem to similar subproblems.

Well, the old adage ain't wrong: To understand recursion, you first need to understand recursion.

There are probably many books and webpages only a single search away.

I would recommend you try to do very simple recursive functions first and then gradually solve harder and harder problems. Make sure that you understand why it works each time you have solved a problem.

Things to practice: factorial, fibonacci, linear search through a list, sum of elements in list, is_even(int), map a function over a list, filter a list, and then try even harder like binary search and quicksort. Once these are done, you can try first hamming distance and then levenshtein distance.

An important thing to remember about recursion is that it is just another programming tool. Like all tools, it works well for what it is intended for, but is a terrible choice when used inappropriately. My suggestion is to study the types of problems where the use of recursion makes a natural solution. In my field (embedded systems), I have found recursion to be useful just a few times over the last 40 years. I am sure it comes in more useful in other fields, but again, just remember it is only one of many tools you will need in the software engineering field.