← Previous
🏠 Homepage
Next Chapter →
Recursion: Function Calling Itself (Wait, What?!)
This is called recursion. It's like asking someone,
"Hey, can you do this?"
And they say,
"Sure, let me first ask myself to do it."
Example: Factorial
You know this math thing:
-
4! = 4 × 3 × 2 × 1 = 24
We can also say: -
4! = 4 × 3!
-
3! = 3 × 2!
-
...and so on.
This makes it a perfect case for recursion!
Non-Recursive Way (Using Loop)
int f = 1;
for (int i = x; i >= 1; i--)
f = f * i;
return f;
}
Easy loop. No drama.
Recursive Way (Using Function Inside Itself!)
if (x == 1)
return 1;
else
return x * rec(x - 1);
}
Breakdown for rec(3)
:
-
rec(3) → 3 × rec(2)
-
rec(2) → 2 × rec(1)
-
rec(1) → 1 ← stops here
Then it unwinds like: -
rec(2) = 2 × 1 = 2
-
rec(3) = 3 × 2 = 6
Boom! You got the answer.
Behind the Scenes: The Stack
-
It's like a pile of plates.
-
Last plate in → First one out.
So when we call functions, info gets pushed on the stack.
When they return, it's popped off.
Just like:
-
Put things on → function starts
-
Take them off → function ends
Recursive calls keep stacking until the base case (like if(x == 1)
) is reached.
If you forget the base case, it’s like stacking plates forever.
Stack overflow!
Library Magic
Want to make your own function library?
Steps:
-
Write function (e.g.
factorial()
infact.c
) -
Compile → You get
fact.obj
-
Use Turbo C’s tlib tool to add it to a
.lib
filetlib math.lib + fact.obj
-
Write a header file
fact.h
with function declaration -
Use the function in any program!
#include "fact.h"
You can even create your own cool collection of:
-
factorial()
-
prime()
-
fibonacci()
All packed into one neat.lib
Summary
-
Functions = Mini-programs inside your program
-
Recursion = A function that calls itself (like echoing your name in a cave )
-
Stack handles the memory behind recursive calls
-
Don't forget a base case or you'll crash the stack!
-
You can create your own libraries and become a function wizard
No comments:
Post a Comment