r/C_Programming • u/yug_jain29 • Jul 10 '26
Question can I skip recursive functions?
a code i can run with the logic of iterative, so why do I have to learn the new concept as complicated as recursive? (ik it's one of important questions in c)
if yes will u pls explain it with a very realistic and simple example
thanks a lot đ
0
Upvotes
56
u/Eric848448 Jul 10 '26
Recursion isnât a C thing. Itâs a Computer Science thing. Understanding it will help you a lot in interviews.
26
u/kabekew Jul 10 '26
Traversing trees and heaps usually uses recursion
13
u/mjmvideos Jul 10 '26
Iâve been working and programming professionally for more than 40 years and have never once needed to use recursion. But Iâve been in the real-time embedded space. There are many situations where recursion is more natural and it takes effort to implement it without.
6
u/PseudoFrequency Jul 10 '26
Some problems are most natural to solve using recursion. A classic example and college assignment is a Sudoku solver. Add a number that is legal at the time. Attempt to solve the puzzle. If all 81 spaces are filled, you have solve it. If not, remove the number you just added and try again with the next legal number at that state/time. It may seem complicated to wrap your head around at first, but it helps to have problems like this that are naturally recursive. Simpler examples are factorial and Fibonacci numbers, but I don't like those as much because they're better off as simple loops. But, they can absolutely be solved with recursion. Do you have to learn it or use it? No. But, it can be an important tool for a programmer. I've got a few more advanced cases of it, typically for decompression algorithms, but that's not really a beginner's topic.
6
u/CuteSignificance5083 Jul 10 '26
Recursion is literally just a function calling itself indefinitely, until some base case is met. That can't be so hard to understand, so I assume you are struggling with applying recursion rather than the idea itself. In that case, you will just get used to it as you see it again and again in future, and there are usually also iterative solutions to the same problem as you yourself stated.
5
u/IdealBlueMan Jul 10 '26
Honestly, I donât use it very much at all. But itâs a very important concept to understand and to be able to implement. When you run into a situation in which recursion is the best solution, you want to be able to do it cleanly. And if you see recursive code in the wild, you want to be able to understand without twisting up your brain.
5
u/WillisAHershey Jul 10 '26
No you cannot skip learning recursion lol.
The exact thing youâre trying to implement may very well be a good candidate for an iterative approach (let me guess⊠factorial?) but there are many problems in computer programming where the iterative approach is not only more cumbersome, but a genuinely bad solution to the problem.
Understanding recursion is a valuable tool to have in your programming arsenal. Just learn it dude. Itâs literally not even that hard.
3
u/CaffeinatedT Jul 10 '26
The entirety of Tree algorithms
3
u/burlingk Jul 10 '26
There are things that are legitimately better to work with in a recursive manner. They are rarely the examples in the book, though, which leads some new learners to assume it's not important.
But it is.
In actual development, it's often good to prefer iteration, but you don't always have the information you need to make iteration make sense.
2
u/mc_pm Jul 10 '26
There are some cases (like working with a tree data structure) where the problem naturally fits a recursive pattern. You might not have got to that point yet, but it's there. And it does come up, I was using it literally yesterday.
2
u/deckarep Jul 10 '26
Donât be scared to learn recursion! In the same way that a function can call other functions, well a function can call itself too!
It just needs a way to terminate so you donât end up in a situation where you have a stack overflow.
Sometimes recursion provides an elegant solution to processing data.
2
u/AndrewBorg1126 Jul 10 '26 edited Jul 10 '26
Recursion is a way of thinking about things, but on your computer it all turns into an equivalent structure made with a stack and loop. You can choose to write it explicitly as a stack and loop if you really don't want to write self referential functions.
Being able to write functions that call themselves can make things much easier to write/read than writing the same logic explicitly as equivalent stack and loop.
You should be able to think about things with recursion, even if you don't want to write it.
2
u/L_uciferMorningstar Jul 10 '26
Learn about trees and graphs. They are easy to traverse recursively. Idk how to traverse iteratively.
2
u/Ch1noXL Jul 10 '26 edited Jul 10 '26
Think of a program where you need to list all of the files found in a directory, including all of its subdirectories and the sub-subdirectories, so on and so forth.
This can be done using recursion.
You write a recursive function that:
What this does is it will search through the directory and each of its subdirectories for files until it gets to a point where there are no more subdirectories to search through.
You could do this with loops, but it would be overly complicated for a scenario like this.
This was the scenario I was put in during an internship and what helped recursion click for me.
Edit: Fixed wording in step 3, had the yes and no cases backwards before.
2
u/MagicalPizza21 Jul 10 '26 edited Jul 10 '26
Recursion is actually fairly simple: a recursive algorithm has a base case and a recursive case.
The base case is a version of the problem you're trying to solve that's so small that the answer is just memorized. A recursive algorithm without a base case will just go on forever, or until the device it's running on runs out of memory or runs into an error. This is an example of recursion with no base case.
The recursive case is the part where the algorithm calls itself, typically on a smaller or simpler version of the problem you're trying to solve. It usually processes this result and combines it somehow with the parts of the input that are excluded in the smaller version.
As an example, let's say you want to find the factorial of a non-negative integer (let's call it n). You can probably figure out the iterative way to do this, but we're talking about recursion here.
The base case for factorial is if n<2; in this case, factorial(n) = 1. Simple, no calculation required.
The recursive case is, well, everything else. So nâ„2. The page I linked has the recursive definition on there: factorial(n) = n * factorial(n-1) for nâ„1 (which also happens to just be 1 when n=1).
So the full recursive algorithm would look something like this:
Does that make sense?
2
u/iOSCaleb Jul 10 '26
You've got it backward. Recursion isn't that complicated, it's just new when you're first learning about it, and that makes it feel hard. Recursive solutions to many problems are often simpler and more elegant than equivalent iterative versions.
Recursive solutions work well when you can do some work to reduce the size of a problem, but it's still basically the same problem. You need two things:
Classic examples are functions like factorial() or fibonacci(), where you get each term by modifying the previous term. For example, factorial(0) = 1; factorial(n) = n * factorial(n-1). The function is only valid for n >= 0. factorial(0) is the base case -- if n = 0, we just return 1 and that's it. For n > 0, you just multiply n by factorial(n-1), which is a slightly smaller version of the same problem. It seems complicated when you try to think about the whole thing at once, but if you just focus on one step it's very simple:
That's not a very complicated example, and you could as easily do that with a loop, but it's good to start simple. Stepping up to something a little more complicated, let's do a binary search for a value in a sorted array. We'll write a function that takes a value and two indexes as lower and upper limits to search. Start by picking an midpoint between the two limits. If the midpoint is the value we want, we're done; otherwise, search either the upper or lower half of the array, depending on whether the value at the midpoint was greater or less than the one we want.
Again, you could do that iteratively, but what's nice about this solution is that you only have to think about one step. Either you've found the value or you haven't, and if you haven't then you just search a smaller part of the array; you don't have to think about how that happens. In the next step the same thing happens all over again: either you've found the number or you haven't, and if you haven't you just search a smaller part of the array...
3
u/_abscessedwound Jul 10 '26
This is more of a computer science question than a C one FYI.
While theoretically every recursive function can be written iteratively, we havenât discovered the iterative approach for a lot of operations, so youâll need to do it recursively sometimes.
Also, existing code (most code), can have recursive functions in it that youâll likely have to deal with, so youâll need to understand recursion.
1
u/NomadicScribe Jul 10 '26
There is really no getting away from recursion. It is a core component of computer science, and frequently the simplest and most maintainable approach to a problem.
1
u/esaule Jul 10 '26
There are codes that can't be written without recursion. (or without resimulating recursion iteratively.)
1
u/solaris_var Jul 10 '26
Some have mentioned tree traversal, but I think an even simpler problem that you can't solve without recursion is, flattening a nested array.
Sure for a nested array with a depth of 2, you can just use multiple loops. But what about a nested array with arbritrary depth?
As an example, how would you flatten an array {1, { 2, 3}, {4, {5, 6} }, { {7, 8}, {9, 10}, {{11}} } , 12} into { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}?
(I just now realized that you mentioned C, where this kind of problem is not commonly taught. Imho this is because C's way of expressing algebraic data types using union can get messy pretty fast.)
1
u/MyTinyHappyPlace Jul 10 '26
Recursion is only complicated if you have no clue about how code works on execution level. Even if you donât like recursion, you should learn everything necessary to it in order to ever understand anything when you debug your software.
1
u/evincarofautumn Jul 10 '26
Recursion and iteration are two different ways of doing induction. Which one you use depends on whatâs natural for the task and what your language supports. A lot of data structures are inherently recursive. For example, a JSON expression may contain JSON expressions, and you need to handle that one way or another.
If youâre using an imperative language like C, recursion is limited by stack memory, because the language doesnât guarantee not to leak space for tail-recursion.
In a functional language like Haskell, you can opt in to using iteration if you want, for low-level code, but normal code is recursive. For example:
You should at least be aware of this, as mainstream languages are nowadays adopting more features from functional programming. In particular, pure transformations of immutable data can avoid a lot of common mistakes that lead to bugs in old-school iterative index-based algorithms.
1
u/Total-Box-5169 Jul 10 '26
Why would you want to nerf yourself like that? Learn how to do it with recursion and without recursion. There are other concepts that you need to learn that take for granted that you understand recursion, so skipping it is a bad idea.
1
u/Fujinn981 Jul 11 '26
Recursion isn't super commonly used, but if you're for example, enumerating and moving through and mapping directories it's great as it greatly simplifies the process which would be painstaking with a loop. Same with any similar structure where using a loop would be very annoying, and would generate more overhead as well as complicate the code needlessly, when the same task could be handled much more easily and efficiently with recursion.
For example, you're in directory A.
In directory A, you have directory B and C.
The code in your function will loop through everything in directory A. Once it sees directory B, it will call itself, but with the source directory being directory B, where it will do the same thing but in directory B.
Once it is done in directory B and all subsequent directories, it will continue to loop through directory A, and then do the same in directory C.
The end result is you have a full mapping of the desired directories and everything in them, which the code will then do whatever it does with that information. There's some caveats such as recursing too much causing stack overflows, but that's easily solved by simply passing a variable through to the function which counts every recursion. Incrementing on every recursion, decrementing on every return. You then set the max value to which the function can recurse, if it hits that value, it returns early, breaking the recursive loop and preventing a stack overflow.
Don't be afraid of recursion, it's a valid technique and is your friend in niche scenarios like the one above.
1
u/pfp-disciple Jul 10 '26
One of the things to avoid in programming is premature optimization. Some things, like list reversal, tree traversal, and some math, are more intuitively done with recursion. You can do the recursion quicker and more obviously at first.Â
1
u/Illustrious_Cod_9593 Jul 10 '26
Bro recursive functions are like being high on drugs I love it
1
u/genafcvpxyr31 Jul 10 '26
In order to learn about recursion, you must first learn about recursion.
From the Oxford English Dictionary:
recursion, noun
see recursion.
You also get recursive data structures, such as lists and trees. Basically, you can't avoid them or recursive functions in Computer Science. Some Turing complete languages don't have loops, so you use recursion instead.
0
u/Dazzling_Music_2411 Jul 10 '26
Because iterative code is generally utilized where data structures and their possible sizes and shapes are more or less already known, especially in a mathematical context.
Recursion is used when you need trees, so its applications are parsing, languages, compilers and computer sciency things, where iteration doesn't have much of a chance.
Incidentally, recusion IS NOT COMPLICATED, it's actually really easy once you get it, because it maps to natural thinking. It CAN seem complicated in C because you have to deal with all that resource allocation-deallocation, etc.
In that case, I would recommend you learn it in Lisp or (even better) in Scheme, where its simplicity shines out without all the clutter. Then, when you understand the core idea, you can go back to implementing it in C with all the labour that entails.
-2
u/ElectronEyez Jul 10 '26
Recursion is just a function calling itself because Big O(n) doesn't want you to know about O(1) tricks. My uncle worked at Bell Labs and said they invented recursion in the 70s to make interview candidates feel bad. Every "recursive" solution can be rewritten as a for-loop with enough duct tape. Wake up.
0
u/[deleted] Jul 10 '26
[deleted] â view deleted comment