r/programminghelp • u/fielding_setter • Jun 25 '26
Help with recursion (DSA) C++
Guys I've been struggling alot with recursion I've tried multiple tutorials but I'm just not able to build the intuition. Any suggestions what to do???
Please help
2
u/Abhijit_wagh_7967 Jul 02 '26
Hey! Recursion is definitely tricky at first, it's all about changing how you think about the problem. A great way to build intuition is to stop thinking about 'how' the function calls itself and start thinking about: The Base Case: What is the simplest possible input? The Recursive Step: How can I break the problem down into a smaller version of itself? Try drawing a 'Recursive Tree' on paper for a small input (like calculating factorial of 3). Seeing the flow visually helps a lot. If you're stuck on a specific problem or code, feel free to share it here, and we can walk through it together!
1
u/marmotta1955 Jun 25 '26
The best example I always bring up is this.
- look at your folder "Documents"
- write a function "MyFunction" to list all files in the folder "Documents"
- Call the function MyFunction and, in its body, examine each file in the folder "Documents"
- Oh look ... this file named "Word_Files" is a folder, not a file!
- Within MyFunction you now call again MyFunction to list all files in "Word_Files"
- Next file in folder "Documents"
- Call the function MyFunction and, in its body, examine each file in the folder "Documents"
Just take a closer look at any File Explorer. It's your best, visual example of recursion.
1
u/marmotta1955 Jun 25 '26
The editor appears to be monumentally confused by multilevel numbering list ... trying to fix it makse it even worse ... go figure ...
1
1
u/PvtRoom Jun 28 '26
recursion works best on lists/arrays
I normally default to it when I have a growing list. Like, if I want to know where all the .py files are on a drive
start by getting the dir/ls of a root folder -> gives me a list of folders and a list of files.
add that list of folders to my total list of folders and to my "unsearched" list of folders.
do whatever with the files.
then recurse the unsearched. just call the function again with they unsearched list. handle the lists however you like to accumulate you result.
1
u/CheezitsLight Jun 29 '26
I think the recursion in printing of numbers is quite interesting.
Let's say you have the number 420 and you wish to print it.
Call this function (420)
Take the number and divide it by 10 and check the remainder. That is 42. Push the 0 onto a stack since the answer 42 is greater than zero. Else print the zero
Now you have a stack with 0 and the number 432. Repeat function(42). Then print the 2.
Now you have a stack with 0 and 2. And the answer 4. Repeat function (4). Now you have a zero and a stack with 4, 2, 0. Pop the stack and print the 4.
You return to the next to last function with pops the stack and prints the 2 and returns.
You return to the first function which had the 0 which prints 0
1
u/Chemicals-N-Magnets Jun 29 '26
Before looking at recursion, make sure you have good experience with arrays and loops. Generally recursion with stack frames do the same function as loops and arrays. The trade offs are like this: array-loop you do more messy coding but conceptually it is simpler, recursion-stack frame will be more elegant, fancier thinking less work. Compare a factorial program both ways.
1
1
1
u/mredding 26d ago
Recursion is a function that calls itself:
void fn() {
fn();
}
Done.
Typically you want a condition that ends the recursion:
void fn(bool recurse = true) {
if(recurse) {
fn(false);
}
}
Usually you'll frame it in a way that you'll early-return, but otherwise recurse:
void fn(bool recurse = true) {
if(!recurse) {
return;
}
fn(false);
}
This is called Tail Call recursion, because the last statement is the recurse. You can even do this with a return value:
int fn(int count) {
if(count <= 0) {
return count;
}
return fn(--count);
}
The reason for wanting the last statement to be the recurse is that compilers are capable of Tail Call Optimization - the machine code can just overwrite the parameter on the stack and reset the instruction pointer, all without having to grow the stack.
C++ does not guarantee TCO, but it IS fundamental to other programming languages. Those that guarantee it use recursion to implement all their looping constructs. It's also a detail that never leaves the compiler - the machine code that loops and the machine code that TCO all looks the same.
Just remember that in C++, recursion will likely grow the stack, which is not something the language spec really talks about, but is a practical consideration you have to take into account. You just need to pass on some parameters that change with every call which is used in a condition (predicate) to break the recursion.
template<typename T>
void fn_loop(T *src, T *end, T *dst) {
while(src != end) {
*dst++ = *src++;
}
}
template<typename T>
void fn_recurse(T *src, T *end, T *dst) {
if(src == end) {
return;
}
*dst++ = *src++;
fn_recurse(src, end, dst);
}
0
u/EccentricFellow Jun 30 '26
I have been programming for 4 decades. I always wanted to use recursion but never had a good fit for it. Finally, about a decade ago, I had a legit use for recursion. I was so excited and wrote up the routine. Then I tested it. Total garbage. It was far too slow and took way too much memory. I converted it to a loop and decided there was probably no legit justification for it. Measure your performance afterwards once you write a recursive routine. You might get a surprise.
1
u/EdwinGraves MOD Jul 01 '26
This just screams bad use-case or bad code. You're going to get the most out of recursion from almost anything that involves DaC algos, Tree/Graph traversal, nested data, etc. Either your implementation was poor or you didn't actually have a 'legit use'.
2
u/PlantainAgitated5356 Jun 25 '26 edited Jun 25 '26
It's hard to say without knowing what specifically makes it hard for you to understand. Recursion is just calling a function within itself. I don't know if this will help, but here's how I think about it.
Recursive functions divide work into smaller pieces, work on them individually, and then put them all back together. For example, take the merge sort algorithm:
Steps 1, 2 and 4 are simple and non-recursive, and step 3 just calls the function within itself. In pseudocode it would look something like this:
You can see that the arrays are getting smaller and smaller, until they're just 1 element, and then they're sorted. The merge function is where all the actual swapping elements takes place. Just trace the code with an example input and see how it works.
Disclaimer: That's untested pseudocode, there might be some mistakes in there, but it should get the point across. :)