Recursive Functions
Learn how recursive functions call themselves to solve problems step by step in BornomalaScript.
Recursive Functions
Recursive functions are functions that call themselves.
They are useful when a problem can be broken into smaller versions of the same problem.
Why Recursion Matters
Recursion is helpful when:
- a task repeats in smaller steps
- the problem has a natural base case
- you want to break down a complex problem into simpler parts
Basic Example
Example: factorial
kaj fact(n) {
jodi (n == 0) tahole {
ferotDao 1
}
nahole {
ferotDao n * fact(n-1)
}
}
lekho(fact(10))
This function calculates factorial by calling itself with a smaller value each time.
How It Works
Recursive functions usually need two things:
- a base case that stops the recursion
- a recursive step that moves toward the base case
In the factorial example:
n == 0is the base casen * fact(n-1)is the recursive step
Without a base case, the function would keep calling itself forever.
Step-by-Step Breakdown
- The function receives a value
- It checks whether the value has reached the stopping point
- If yes, it returns the final answer
- If not, it calls itself with a smaller value
- The results combine as the calls return
Why This Example Matters
Factorial is a common recursion example because it clearly shows the base case and the shrinking step.
It is a good practice problem for learning how recursive thinking works.
Try These Variations
Practice with different base values:
kaj fact(n) {
jodi (n <= 1) tahole {
ferotDao 1
}
nahole {
ferotDao n * fact(n - 1)
}
}
lekho(fact(5))
You can also test smaller values to see how the stopping rule behaves.
Common Mistakes
Beginners often make these mistakes:
- forgetting the base case
- making the recursive step move in the wrong direction
- using recursion when a simple loop would be easier
- not understanding when the function should stop
Practice Task
Try writing recursive functions for:
- countdown
- factorial
- sum of numbers from 1 to n
Quick Checklist
Before moving on, make sure you can:
- identify the base case
- identify the recursive call
- explain why the function stops
If yes, you understand the basic idea of recursion in BornomalaScript.