Saturday, January 20, 2018

Recursion


Recursion


Consider the problem of printing 'Hello' 10 times.





How do we do this?  The obvious way is to use a for loop.  Assuming parameter N to hold the number of 'Hello', we then have the following code:

      def sayHello(N):
            for i in range(N):
                  print('Hello')

There is an alternative way: to define the function recursively.  A recursive function is a function that calls itself. In the context of this 'Hello' problem, we would recurse depending on the value of N.

      def sayHello(N):
             if N == 1
                  print('Hello')
                  return

            sayHello(N-1)

Here, sayHello is calling itself, and it will keep calling itself until N == 1. Visually, one can understand it as shown below:


Importantly, in doing recursion, there must be a 'base' case, the stopping point. A function cannot keep calling itself till about forever. There must be a stopping criteria.  

So ok, the darn thing work? Why should we bother about recursion? The recursive function above certainly seems longer than the non-recursive one. Well, there are cases, as we shall see later, where recursion simplifies the presentation of a code. We will look at that in future posts.



No comments:

Post a Comment