r/C_Programming • u/yug_jain29 • Jul 15 '26
Question Any homework to understand recursion better?
hi every1, i am now sure i understand what recursion MEANS, but i actually don't know how to implement it and what to write while coding, so any BEGINNER friendly examples, homework? or a concept to understand the structure of recursion much better?
and does every recursive function necessarily have (n - 1) ? to get to the base case?
12
Upvotes
4
u/kokolo17 Jul 15 '26
The simplest recursive algorithm is probably calculating the factorial. For something more practical, you can always do something with tree data structures
2
u/melodicmonster Jul 15 '26 edited Jul 19 '26
Let's say I want to print N numbers in ascending order. Consider the following snippet:
This function starts by defining the end of the recursion, which is a good place to start with any recursive call. In this case, we know we don't want to print anything less than 1, so the function returns immediately if that is the case. Code:
if (i <= 0) return;If not the case, the function immediately recurses so that the print statements (the next step) are in proper order. Otherwise, printing first would print them in descending order. Code:
count(i - 1);Finally, each one prints its value and returns to its caller it so that the caller can also print its value. Code:
printf("%d\n", i);For example, let's say I call count(3). This is what happens:
- count(3) checks i and passes. It immediately calls count(2) and waits for count(2) to return.
-count(2) checks i and passes. It immediately calls count(1), and both count(3) and count(2) are waiting.
- count(1) checks i and passes. It immediately calls count(0); count(3), count(2), and count(1) are waiting.
- count(0) checks i and fails, returning immediately to count(1). count(2) and count(3) are waiting.
- count(1) prints "1" and returns to count(2). count(3) is waiting.
- count(2) prints "2" and returns to count(3). No calls to count are waiting.
- count(3) prints "3" and returns to the originall caller.
To be clear, this would be better as a non-recursive (iterative) call. It is just for illustration purposes. I generally avoid recursion in production code regardless of language unless certain optimizations are available or there are no other (better) alternatives.
Edit: I originally used code formatting instead of code block.
41
u/Pupation Jul 15 '26
In order to understand recursion, you first have to understand recursion.
28
u/AlexTaradov Jul 15 '26
The easiest practical way to understand it is to make a program that walks the whole hard drive tree and prints the full path and a size of each file. The functions to walk the directory are in the standard library, so the amount of OS specific work is minimal.
You can also do it both recursively (easy) and not to see the difference.
You don't need (n-1), but you need a stopping condition. In case if directory listing that condition would be "no more files to list".
7
u/AKostur Jul 15 '26
Towers of Hanoi problem?
6
u/Nysandre Jul 15 '26
Fibonacci numbers
4
u/EducationalTackle819 Jul 15 '26
Recursion is generally useful when you can take a large problem, and recursively break it into smaller problems that are dependent on the results of each other. The common example is factorial, because to know 7!, you must know 6! And so on.
It doesn’t have to be n-1 to get to the base case though. You get to define how you break the problem up. You implement binary search with recursion, where each recurse shrinks the search space in half until you reach the result. That isn’t n-1, that is logarithmic.
Just think of recursion as being useful for when a problem can be broken into sub problems of the same nature that will eventually terminate. E.g. hitting 1 in factorial, or finding the element in binary search (or that it doesn’t exist)
1
u/AndrewBorg1126 Jul 15 '26
Are you really sure that you "understand what recursion MEANS"?
A function that refers to itself is recursive. The base case(s) can be anything useful. The amount by which values change at each recursive depth does not have to be 1, and also does not have to even be constant, and also does not have to be conceptually numerical.
3
u/mc_pm Jul 15 '26 edited Jul 15 '26
Every recursive function needs two paths out of the code: One cuts the input down by some amount (sometimes -1, more often by spitting it in half) and then calls itself one or more times; the other drops out of the recursion completely (when you are done).
2
u/rupertavery64 Jul 15 '26
A recursive function is one that calls itself. That much you already understand. It's a loop. And like all loops, it needs to have an exit condition, otherwise it becomes an infinite loop.
However, the difference between a regular loop and recursion is that every time a function is called, all local variables (and the return address) are pushed onto the stack, and without an exit condition, you rapidly run out of stack space, and get acquainted with the infamous stack overflow.
So it doesn't have to be n - 1, it is any condition that results in not calling the function again.
If you are familiar with structs and pointers, you can create a tree structure with a root node and several child nodes, that have child nodes.
Your exit condition would be if the node does not have any child nodes.
As a real-world example, you could write some code to traverse a directory on your drive recursively. Your input to the function would be a path. You would have some code that lists the sub directories of the current path. You don't even need to pass a value to trigger the exit condition, because the condition is in the function itself (no more child directories found).
2
u/Paxtian Jul 15 '26
Implement a Fibonacci calculator using recursion. Just don't ask it to calculate beyond the 70th or so term unless you also implement memoization and handle large numbers properly.
F(n) = F(n-1) + F(n-2)
2
u/Sellorio Jul 16 '26
Yeah check out this comment for everything you need to know about recursion:
https://www.reddit.com/r/C_Programming/comments/1uxbmad/comment/oxt2yxw/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
1
u/dajoli Jul 15 '26
I mostly figured out recursion with the problems on CodingBat. They are tested via Java, but you need very little Java-specific knowledge to do them.
1
u/HashDefTrueFalse Jul 15 '26 edited Jul 15 '26
If you already understand what it is and what is happening to the stack, the best advice for writing recursive solutions I can give is to look at lots of example solutions where they have identified a way to repeatedly solve the same problem on smaller and smaller portions of the input data until the base case provides the starting point for the simplest case. It's quite unintuitive at first, not one of those things where you're going to read the right explanation and suddenly get it, but you will if you start with simple examples and try to come up with your own problems and write your own solutions.
1
u/R_051 Jul 15 '26
Try this https://www.reddit.com/r/C_Programming/s/sH6qVcyqVu
1
u/Weshmek Jul 15 '26
I was taught recursion in first year CS in university. They taught us Racket which is based on Scheme, which is designed around using recursion efficiently. Since C doesn't have tail-call optimization (some compilers enable it) it's really not ideal for recursive algorithms.
1
u/genafcvpxyr31 Jul 15 '26
#include <stdio.h>void head( int arg ) {if( arg > 0 ) {head( arg - 1 );}printf( "%d\n", arg );return;}void tail( int arg ) {printf( "%d\n", arg );if( arg > 0 ) {tail( arg - 1 );}return;}int main() {printf( "head function...\n" );head( 5 );printf( "tail function...\n" );tail( 5 );return 0;}If you get the above code you're halfway there.
The head function calls itself with the value of arg-1 before printing the value of arg, that self call does the same with arg-2... all the way down to 0. Six calls to head(int) (including the call from main() ) are made before anything is printed on screen:
call with 5 from main(), call with 4 from head, call with 3 from head, call with 2 from head, call with 1 from head, call with 0 from head...
The if( arg > 0 ) statement returns false, no more calls...
prints 0 from last call, prints 1 from second to last call, prints 3 from third to last call, and on and on til five is printed, then goes back to main().
The tail function prints the given value of arg first then calls itself with arg-1... This time it's:
call with 5 from main(), print 5, call with 4 from tail, print 4, call with 3 from tail, print 3, call with 2 from tail, print 2, call with 1 from tail, print 1, call with 0 from tail, print 0...
The if( arg > 0 ) statement returns false, no more recursive calls, jumps back to main().
Printout:
head function...
0
1
2
3
4
5
tail function...
5
4
3
2
1
0
1
u/sciencekm Jul 15 '26
Problems that are recursive in nature simply means that a portion of the problem is defined as the problem itself.
As an example, if you want to SUM the values of an array with N items, you can define this as:
SUM(A[0..(N-1)] ) :
when N == 1, A[0]
when >= 2, A[0] + SUM(A[1..(N-1)])
Notice how the definition of SUM is as SUM itself.
You should now be able to write function that returns the first and only item of the array if the array size is 1, or return the addition of the first item with the result of calling the function again, but with the remaining array items.
float sum(float array[], int size) {
if (size <= 0) return 0.0;
return size == 1 ? array[0] : array[0] + sum(array + 1, size - 1);
}
The above example is of course not the ideal way of summing up an array, but it was chosen to demonstrate a very simple recursion.
1
u/Kindly-Department206 Jul 15 '26
You can't learn recursion by reading Reddit. Find a textbook for novices on C programming. Not a reference manual for the C language, a textbook whose purpose is to teach novices to program. Familiarize yourself with how function calls work by reading that chapter. Then read the chapter on recursion.
If there is no chapter on recursion in the book you chose, find a textbook where it is given a full chapter.
1
u/Evening_Ticket_9517 Jul 15 '26
You can use ctutor. Provides very easy visualization of topics like these. Go to the website and write a small recursive function like fibonacci for example.
1
u/Independent_Art_6676 Jul 15 '26
try doing the examples you already did using a stack data structure and a loop. All recursion is doing is hiding a data structure (the stack; its using the call stack as if a data storage/structure) and looping. If you can solve the problem with a stack and a loop, then a little thinking can convert that syntax to recursive to do the exact same thing.
base cases vary. You could implement a recursive binary search with n/2 instead of n-1 for some data structures (it would be like how a search tree works).
1
u/thank_burdell Jul 15 '26
Canonical example is probably to implement a Fibonacci sequence generator both iteratively and recursively.
1
u/Wake95 Jul 15 '26
The card game War is a good example. Whenever there is a war, the war can either end or lead to another war.
1
u/WittyStick Jul 15 '26 edited Jul 15 '26
Not every recursive function is primitive recursive, but most practical ones you will implement are, and you should practice using them. Non-primitive recursive functions have their uses, but are not guaranteed to converge, and even if they do, they may not be practical to compute, and it may not be possible to prove they even terminate.
For practicing, have a try at implementing functions over singly-linked lists using recursion rather than while/for loops, with the termination condition being either a nul-terminator or using length indexed lists where counting down to zero is the termination condition.
1
u/Recycled5000 Jul 15 '26
Try to separate the action (the what) of a recursive function from its internal implementation (the how).
You want to read the implementation of the recursive function (the how) and yet when you see it making a function call then switch your mental model to the what that call will/should do (and not how it will do it). Then continue to absorb the how of the implementation.
To reiterate: when you see function calls within an implementation, try to see them as a tool that accomplishes something without considering their internal how, so you can stay on one level and see how just one call / one level of the function works.
1
u/Ecstatic_Student8854 Jul 15 '26
You don’t need to have every case rely on (n-1). In fact you can recurse on things other than numbers.
The best way to think about recursion is to think of like so: given the solution to some smaller problem, can I solve the big problem? You then assume you have that solution by recursing, and implement a base case for when the problem cannot be further reduced.
For example, one can implement a binary search recursively in the following pseudocode:
```
# returns index of target value in sorted array, or None if it is not found
def binsearch(array, target, low_idx, high_idx):
if low_idx==high_idx return None
middle = low_idx + ( high_idx - low_idx ) / 2
if array[middle] = target return middle
if array[middle] > target then return binsearch(array, target, low_idx, high_idx/2)
if array[middle < target then return binsearch(array, target, low_idx/2, high_idx)
```
There is no clear recursive call to n-1, but nonetheless we reduce the window we look in with each recursive call. We must either at some point find the target or the window size becomes smaller and smaller (eventually becoming 0), in which case the target is not in the array.
This seems very convoluted , but it gets easier when you do it more. Just practice.
1
u/silvertank00 Jul 15 '26
Think about it like this:
You go to watch a movie at the cinema, you have seat reservation to row 15 but the row numbers are not printed out anywhere.
How would you determine witch row is the 15th? As far I can see, you have two options:
A) go to the bottom row and count upwards
B) in the row in front of you: ask a person "which row are they in?" Add that, "if they don't know, ask the following person that is in front of them with the EXACT instructions". ( Lets say there are 3 rows, with X,Y,Z person: You ask X, they dont know so ask Y, they dont know either, so ask Z. Z knows they are the first so passes the info UPWARDS. So now Y knows they are the second, tells that to X, and they tell you they are in the third row.) (you -> X -> Y -> Z -> Y -> X -> you)
A) is dynamic approach B) is recursive
1
u/knouqs Jul 15 '26
Simple recursive program is the Fibonacci sequence. It's a horrible solution recursively, but shows you exactly what recursion does as it's a pretty simple three-line recursive function.
After you see the recursive solution, you'll better appreciate the iterative one. However, don't be fooled -- recursion has it's place. This problem is for demonstration purposes only.
1
u/Loud_Ask_3408 Jul 15 '26
Nesso Academy, it is a YouTube chanel, watch their videos about recursion in C.
1
u/Loud_Ask_3408 Jul 15 '26
Neso Academy, recursion in C.
Neso Academy is a YouTube channel.
1
u/ScallionSmooth5925 Jul 15 '26
Try to write something without loops in a functional style. For example binary sort
1
u/v_maria Jul 16 '26
directory crawler
1
u/27K-Interactive Jul 16 '26
I strongly suggest the Tower of Hanoi problem to learn recursion. It's safer than thrashing your filesystem and is a very finite problem to solve. If you can understand Tower of Hanoi, you can understand any recursion problem.
1
u/Vasbrasileiro Jul 16 '26
This might be controversial, but you should learn correctness proofs, especially inductive ones. I only began to fully understand recursion once I understood induction, and that writing a recursive algorithm is basically writing a proof by induction.
1
u/wsppan Jul 16 '26 edited Jul 16 '26
Imagine building a super tall tower of toy blocks. You don’t know exactly how many blocks are in the whole pile, so you decide to use recursion to find out:
The Rule: If you only have 1 block left, you just hold it and say, "That's 1 block!" (This is called a Base Case).
The Call: If you have more than 1 block, you put one block aside and tell your clone to count the rest of the pile. You then add your 1 block to whatever number your clone tells you.
Here is what that looks like as a C99 function to count a stack of blocks:
So basically, you need to find the base case and unwind the stack you have been building while checking for that base case when found.
When this runs, your function takes 5 blocks. Since it's not 1, it holds 1 block and calls count_blocks(4). That one calls count_blocks(3), which calls count_blocks(2), which calls count_blocks(1). When it finally hits 1, all the copies of the function start answering backwards, adding all the blocks together until they reach 5.
1
u/TPIRocks Jul 18 '26
The K&R C book contains good examples of using linked lists, binary trees and recursion when processing them. I would ask AI to show you some examples.
1
u/f0xw01f Jul 19 '26
The goal of recursion is to solve a problem by first solving a slightly smaller problem, and then adding a little bit of extra work. As a trivial (and impractical) example, if you wanted to find the product of all the integers between x and y, you could solve this by first finding the product from x to y-1, and then multiply by y. So your function would call itself with the slightly smaller range, and then multiply that result by y and return.
The function must be aware of the base case (the point at which it must stop recursing). This happens when x==y, and in that case, it simply returns x.
0
u/[deleted] Jul 15 '26
[deleted] — view deleted comment
1
u/[deleted] Jul 18 '26
[removed] — view removed comment