Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is recursion and how does it work?

Tags:

Could someone please explain what exactly recursion is (and how it works in Ruby, if that's not too much to ask for). I came across a lengthy code snippet relying on recursion and it confused me (I lost it now, and it's not entirely relevant).

like image 925
omninonsense Avatar asked Jun 20 '11 21:06

omninonsense


People also ask

What is recursion in programming in simple words?

In computer science, recursion is a programming technique using function or algorithm that calls itself one or more times until a specified condition is met at which time the rest of each repetition is processed from the last one called to the first.

What is a good example of recursion?

A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What is recursion and how do you implement it?

Many programming languages implement recursion by means of stacks. Generally, whenever a function (caller) calls another function (callee) or itself as callee, the caller function transfers execution control to the callee. This transfer process may also involve some data to be passed from the caller to the callee.


1 Answers

A recursive function/method calls itself. For a recursive algorithm to terminate you need a base case (e.g. a condition where the function does not call itself recursively) and you also need to make sure that you get closer to that base case in each recursive call. Let's look at a very simple example:

def countdown(n)
  return if n.zero? # base case
  puts n
  countdown(n-1)    # getting closer to base case 
end               

countdown(5)
5
4
3
2
1

Some problems can be very elegantly expressed with recursion, e.g a lot of mathematical functions are described in a recursive way.

like image 100
Michael Kohl Avatar answered Oct 12 '22 19:10

Michael Kohl