-1

Can someone explain how does this code work? It is a code on recursion js from the codeacademy. The code determines rate of growth using The Fibonacci sequence. The output of the code

var height = growBeanstalk(5) // 5
var height = growBeanstalk(8) // 21 etc. 
(4) => //3 (3) => //2

Thank you in advance!

function growBeanstalk(years) {
// Base case
if (years <= 2) {
  return 1;
}   
// Recursive case
return growBeanstalk(years - 1)+ growBeanstalk(years - 2);  
}

// Set the height of the beanstalk using your function
var height = growBeanstalk();

console.log(height);
Prune
  • 76,765
  • 14
  • 60
  • 81
neur.log
  • 27
  • 4
  • Possible duplicate of [JavaScript Fibonacci breakdown](http://stackoverflow.com/questions/18980531/javascript-fibonacci-breakdown) – Prune Dec 06 '16 at 22:02
  • Stack Overflow has many good explanations of recursion using the Fibonacci sequence; several are in JavaScript. Where are you confused after doing your research on the topic? – Prune Dec 06 '16 at 22:07
  • I am confused for example in case of growBeanstalk(8) it gives 21, I understand it is 8+13 but why and where is the statement? why until 5 it returns 5, 6=>8, 7=>13. Why 6 returns 8? – neur.log Dec 07 '16 at 00:19
  • You didn't do your research? [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number). – Prune Dec 07 '16 at 01:37

1 Answers1

0

Basically, when you call growBeanstalk it will of course, execute that function, first it checks if the number is 2 or less, and that is what is called the "base case", which would be the case in which the recursion is ended.

The other part of the function, is the recursion itself, is basically calls itself again, subtracting 1 and 2, and therefore making sure that the function will sometime end.

This is an example of how the function gets called, when you call with 4:

growBeanstalk(4) -> 3
    |----growBeanstalk(3) -> 2
       |---growBeanstalk(2) -> 1
       |---growBeanstalk(1) -> 1
    |----growBeanstalk(2) -> 1
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • Thanks for explanation, but how does it work? I mean recursion, like in case of 5? Because 5-1=4, 5--2 = 3, 4+3 =7, but it returns 5 and where is the statement or conditional for it, which determines Fibonacci? Sorry, I am just a beginner. – neur.log Dec 07 '16 at 01:14