Well if I had known earlier that I
had to talk about recursion this week, I would have not gone into much detail
as I have in week 4 when recursion was being taught. Therefore, this entry in
the slog will be quite similar to that of week 4.
So to
the question of what recursion is. Recursion is simply put, a function where it
attempts to call upon itself repeatedly to get a final value or solve a
problem. This is a powerful and unique technique where by the programmer does
not need to write excessive code to bring about a solution to a problem where
it would seem it would have numerous outcomes and or iterations as such code
will have to be written iteratively. Writing code iteratively to solve a
lengthy problem with seemingly unknown number of iterations can be both tedious,
difficult, impossible and or potentially inefficient. However, it is not say it
is the best solution to everything. There are times where writing iterative
code is simply easier to read and write due to not having to trace it through
multiple layers of code as it calls itself repeatedly.
As a
rule of thumb, if one knows precisely the number of iterations the code would
require to fulfill its purpose, one would write code iteratively. Whereas if
the code can have multiple iterations that the programmer cannot foresee
depending on the parameters given in a function, one would use a recursive
function so that the computer would figure the outcome by itself.
An
example would be the code written to draw a Sierpinski’s Triangle whereby 2
integers will be provided, the number of triangles as well as the number of
dots. As one can see, the code can be written iteratively but will be both
tedious and long. However, a recursive function exists whereby it not only
shortens the code, it allows other programmers to understand the function of
the code to draw the triangle depending on whatever the user inputted.
As for
my person opinion on recursive functions, they are quite useful albeit painful
to analyze when it requires multiple iterations as I easily can get lost in the
code. And the fact that it is easy make a single mistake thereby get a wrong
answer at the end. Also my opinion as to when recursive functions should be
used is explained above. (Use recursive if one does not know the number of
iterations the code must go through to produce a useful output and or purpose. Otherwise
write and use iterative code as it is often simpler to analyze and understand.)