r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

105

u/NewInHere__ Apr 05 '22

recursion, just... recursion

71

u/dkToT Apr 05 '22

Basically a function that will call itself until a certain criteria or situation is satisfied. Once it is satisfied, the result will be returned to the parent function call all the way back to the top. This will help with clean code but only if you know your functionality follows a certain pattern.

A great example of this is the fibonacci series and why it was used in alot of early interview questions. The fib(n) is equal to fib(n-1) + fib(n-2). With recursion you can use this pattern to do the calculation for fib(n-1) and fib(n-2) where fib(n-1) = fib(n-2) + fib(n-3) and fib(n-2) = fib(n-3) + fib(n-4), etc....

Super useful and clean if you now the exact pattern and expectation (traversing a tree, etc..) of what you are building but I personally don't see this used often.

2

u/[deleted] Apr 06 '22

I can understand that Recursion repeats itself. but every code repeats the process it is doing, all the for/while loops that i have used in code is also repeating. so does that mean, i can apply recursion to every program ??? or is there any limitation ??

2

u/username-256 Apr 10 '22

Good question. The answer is to do with how recursion is implemented.

While recursion is in theory equivalent to iteration, since every recursive algorithm can be implemented by an iterative algorithm, in practice recursion nearly always uses more memory. The extra memory is used when the implementation adds data (such as the function return address) onto the machine call stack. The data can also include the call arguments (the values you pass to the function parameters).

In some languages and some compilers a version of recursion called tail recursion can be used (or recognised by the compiler) where extra data is NOT added to the stack.

So no, you shouldn't apply recursion to every problem. Real-world problems such as limited (virtual) memory get in the way. Meaning that after MANY recursive calls your program crashes with an "out of memory' condition.