Recursion in PSeInt: solved examples
3 examples
How it works
A recursive function calls itself with a smaller problem. Factorial is the classic example: 5! is 5 times 4!, and 4! is 4 times 3!, all the way down to 1.
Every recursion needs a base case: the point where the function answers without calling itself again (if n is 1, the factorial is 1). Without it, the calls never end.
Recursion also solves problems like the Towers of Hanoi or merge sort. Following it step by step, watching every call, is the best way to understand it.
Short example
The least you need to see it work. Copy it or open it in the editor.
Funcion r <- Factorial(n) Si n <= 1 Entonces r <- 1 SiNo r <- n * Factorial(n - 1) FinSiFinFuncionAlgoritmo FactorialTest Escribir "5! = ", Factorial(5)FinAlgoritmoWhat it prints:
5! = 120Opens in the browser editor, nothing to install.
Solved exercises
Each exercise comes with the full code, its flowchart and a sample run.
Merge Sort
Splits the array in halves, sorts each one recursively and merges them.
AdvancedQuicksort
Picks a pivot, splits smaller from larger values and sorts each side recursively.
AdvancedTowers of Hanoi
Solves the classic tower puzzle step by step.
Advanced
In the language reference
The instructions involved, explained one by one.
Other concepts
Codoritmo is an independent, open-source project inspired by PSeInt and compatible with its syntax. It is not affiliated with the PSeInt project. Official PSeInt website.