DEV Community

hy86592
hy86592

Posted on • Updated on

Finally Understanding Recursive Functions

I used to have a hard time wrapping my mind around recursive function. Today, I learned 3 characteristics about recursion that makes them easy to understand.

The 3 characteristics of recursive functions:

  1. Recursive functions have a state that is represented by a parameter value.
  2. When calling the inner function, ensure that the parameter (state) must be modified in some way that brings it closer to the 'break condition' and eventually meet it.
  3. Set the 'break condition' for which the inner function is not called again (i.e. breaking the recursion).

Let's see examples.

Function #1

def run():
  run()

run()
Enter fullscreen mode Exit fullscreen mode

This will run until the stack overflows because it's just running itself continuously.

Function #2

def run(n):     # the state is represented by the value n
  run(n)        # no break condition; no change of state (n)

run(10)
Enter fullscreen mode Exit fullscreen mode

This will also run until the stack overflows because there is no breaking condition.

Function #3

def run(n):
  if n == 10:      # break condition (always unsatisfied)
    run(n)         # no change of state (n)

run(10)
Enter fullscreen mode Exit fullscreen mode

This will also run until the stack overflows because the state (n) always satisfies the condition for running.

Function #4

def run(n):
  if n == 10:      # break condition (always unsatisfied)
    run(n)         # no change of state

run(5)
Enter fullscreen mode Exit fullscreen mode

This will never run a second time because the state (n) never meets the conditions for running again.

Function #5

def run(n):
  if n > 1:     # breaking condition (satisfied until the state meets breaking condition)
    run(n-1)    # continuous change of state

run(10)
Enter fullscreen mode Exit fullscreen mode

This will run recursively until the breaking condition is met.

There you have it. A recursive function has a state that is represented by a parameter value and requires a change of state (n) which eventually meets the 'breaking condition' of the function.

I hope this helps.

Top comments (4)

Collapse
 
cschneider profile image
Christian Schneider

I think the last example is wrong. It should be
if n > 1 :

Collapse
 
hy86592 profile image
hy86592

Thank you for the review. Changed! :)

Collapse
 
shantanukr profile image
Shantanu

Yes

Collapse
 
paul_ehmig profile image
Paul Ehmig

Correct, and run(n) calls the function n-1 times. run(1) is the last call in the chain with your fix.