function fib(num){ if(num<=2) return 1; return fib(num-1)+fib(num-2); } document.write(fib(6)); | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

function fib(num){ if(num<=2) return 1; return fib(num-1)+fib(num-2); } document.write(fib(6));

//output= 8 //do u have any explanation?

23rd Jun 2017, 1:19 AM
islam moheb
islam moheb - avatar
1 Answer
+ 14
The process is called recursion, in which a function keeps calling itself until the base case (num<=2 is base case for this example) occurs. And this program is printing 6th number of Fibonacci sequence. Now what's a Fibonacci sequence? The first two numbers are 1, and the next numbers should be the sum of the previous two. 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and it goes like this. So, the 6th number is 8 as you can see. How does it work? The function is called for argument 6. fib(6) = fib(5) + fib(4) // the values are unknown = fib(4) + fib(3) + fib(3)+fib(2) // breaking down = fib(3)+fib(2) + fib(2)+fib(1) + fib(2)+fib(1) + 1 // now since we know the values of fib(2) and fib(1) according to the base case we can get the other values as well = fib(2)+fib(1) +1 + 1+1 + 1+1+1 = 1+1+1+1+1+1+1+1 = 8
23rd Jun 2017, 2:28 AM
Shamima Yasmin
Shamima Yasmin - avatar