Given a number return the nth number of the fibonacci sequence

E.g. First ten fibonacci sequence are 0,1,1,2,3,5,8,13,21,34,55.

The above sequence is formed by adding the previous two numbers to generate the next one. 0 and 1 are considered as base case values.

Let’s look into the code to return the nth number of the fibonacci sequence.

def fibonacci={int n->
    def a = 0, b= 1;
      n.times{ // times is used to for looping n times 
       (a,b) = [b,a+b] // groovy way of multiple assignment where a is assigned b and b is assigned  a+b
     a // no need of explicit return statement since groovy treats last statement as implicit return