In this short article we are going to explain what a recursive function
is and how to implement recursion or create recursive functions in a
programming language. The language to be used in this example is Scilab.
As a general concept, we can say that a recursive function is one that
calls itself to solve itself. In other words, a recursive function is
solved by nested self-calls, by changing the value of a parameter in
every self-call. Through nested self-calls you get new values that are
used to calculate the value of the original call. Don’t worry, we’ll
see an example.
The process of recursive calls always has to end up in a call that is
solved directly, without the need of invoking the function again. This
step will always be needed in order to avoid a never ending loop.
A typical example of recursion would be the factorial function. The
factorial process is a mathematical function that is solved by
multiplying that number times all of the previous natural numbers, so
For example, the factorial of 4 equals 4 × 3 × 2 × 1. If we look the
example of 4 factorial (a factorial is expressed mathematically with an
exclamation mark, as in 4!), it can be solved as 4 × 3! In other words,
we can calculate the factorial of a number by multiplying that number
by the factorial of that number minus 1. In mathematical terms, that is
n! = n ×
In the case of the factorial function, we have the basic case that the
factorial of 1 equals 1, and it can be used as a final point to the
Now, we are going to carry out the code of the recursive factorial
start the definition as usual.
fact = my_factorial(n)
is the last case within the recursion.
eventually reach this point.
if n ==
fact = 1
is the general case.
Notice that we're calling this function and decrementing
fact = n * my_factorial(n-1)
we just close the function
We can call it from the main code, like this:
'use your own path here, or delete this line...';
// load the function into memory
// compare the built-in function with our own one
n = 8
n = 15
And the answer on screen would be:
As you can see, the recursion doesn’t represent any problem for Scilab
and in fact it is a very useful tool for programming appropriate
algorithms. At the beginning, this concept can be hard to understand,
but it’s an excellent way of solving some problems with some
There are some algorithms that are mainly solved through recursion, or
at least, that’s a more direct, straightforward or elegant solution.
For example the exploration of some data structures, such as tree
types, whose solution tends to perform well when recursively reviewed,
in order to make sure that all the branches of the tree have been
See the explanation about recursion in Matlab
'Recursion in Scilab' to home
From 'Recursion in Scilab' to Scilab