0

Where can you implement recursion

Where can you use recursion? Give examples.

3rd Nov 2018, 1:09 AM
OfficialMuffin
OfficialMuffin - avatar
6 Respostas
+ 4
I submitted a lesson to do everything using recursion. This program contains the details and is my implementation for it. It is coded in Kotlin, but should be understandable to you. https://code.sololearn.com/c0g34cgteZjA
3rd Nov 2018, 2:29 AM
John Wells
John Wells - avatar
+ 3
Recursion is when a function calls upon itself again and again with a given base case to terminate. Like if you're given to find the factorial of a given number using recursion... It can be done like #define the function def fact(n): # it's the base case if n<1 and n>=0: return 1 else: #this is the recursive call return n*fact(n-1) This is in python but you can implement the same in any language.
3rd Nov 2018, 1:41 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 3
If you just know how the recursion works and what should be the base case then you can use it in many areas. The above example was just to show you what recursion is. Having idea of recursion, you can implement it in many problems, like on some GUI as well. Other common use cases might include sorting data, traversing hierarchies, e.g. website crawlers, directory comparisons, etc. Of course, one can always use loops to do the same thing but recursion makes the code shorter to implement.
3rd Nov 2018, 1:58 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
How else could you use it apart from factorial and numbers?
3rd Nov 2018, 1:43 AM
OfficialMuffin
OfficialMuffin - avatar
+ 1
You can use recursion practically on every problem that can be broken into smaller problems of the same kind. In other words, problems that you can state with a recursive description: You have already seen: factorial(n) = n * factorial(n-1) Merge sort: sort(array) = 1. sort(left half of array) 2. sort(right half of array) 3. merge here sorting the full array is solved by solving the problem for the left and right halves of the same array Tree walks: (e.g.) in-order(whole tree) = in-order(left-branch) operate-on(root) in-order(right-branch) a branch is again a tree but smaller in size. You see the general pattern, i guess. If you can express the solution of your problem in terms of the solutions to the same problem of a smaller size, recursion is applicable.
3rd Nov 2018, 8:15 AM
Leif
Leif - avatar
0
Most loops could be replaced by a recursive function, some problems are easier to solve with a recursive function, such as printing all the elements​ of binary tree in order.
3rd Nov 2018, 2:01 AM
Jared Bird
Jared Bird - avatar