32) Recursions¶
There’s two ways to solve a problem that iterates:
Iterative Solutions (Loops)
Recursive Solutions (Recursions)
There’s nothing that can be solved only with Recursive Solutions.
If something can be done with Recursive Solutions, then it can also be done with Loops.
Iterative Solutions are usually faster and take less memory, but Recursive Solutions are easier from a designing perspective, and are especially useful for Tree Like structures and shortening code.
But it’s still limited. There’s solutions that can be done with Loops but can’t be done with Recursions.
Data Structures is where the fun begins. I’ll be doing that in Semester 3.
1 2 3 4 5 6 7 8 9 | |
This outputs Hello World! 5 times.
A function is called a Recursive Function if it calls itself within its own code.
1 2 3 4 5 6 7 8 9 10 | |
Don’t actually test run that. It’s an infinite loop. It will cause a Stack Overflow. Yes, just like the website. It’s an infinite loop because there’s no stopping condition.
For a Recursive Function, there’s two requirements:
Base Condition
Recursive Call
A Base Condition is necessary so the recursion only continues until that point. When that condition is no longer true, it stops.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
The only way to actually properly understand Recursion is through a visual explanation of how Stacks work. Unfortunately, at the time of writing, Recursion is a weak topic of mine and I’m not very skilled at it yet. On top of that, this is only a minor topic of Semester 1 for my CS Program, so I’ll go way more in depth in Semester 2, where it’s a major topic.
But if you want to know more about them then there’s many YouTube videos explaining them. It’s important to know how the memory itself works so this can be understood.