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.

15

u/TheTomato2 Apr 05 '22

To add on to this, recursion, at least for me, was confusing because sometimes it's taught before they teach you how or what the main stack in program works/is. It's really simple once you learn its just the same function calling itself and pushing another instance on to the stack and then using returns to unwind the stack. That's all recursion is. It's also makes it easy to understand why probably shouldn't use it unless the problem really begs for it.

4

u/above_all_be_kind Apr 06 '22

Yes, this was exactly it for me. Recursion, as a concept, was perfectly understandable but it wasn’t until I understood how its code-based implementation actually worked that I was able to start getting comfortable with creating it from scratch. The whole secret to understanding its code-based implementation, as it turned out, was comprehension of stacks.