1.

Read the following function int fib(int n) { if (n<3)return 1; else return (fib(n – 1) + fib(n – 2)); } 1. What is the speciality of this function 2. How does it work? 3. What will be the output of the following code?

Answer»

1. This function is a recursive function. 

That means the function calls itself. 

2. It works as follows 

  • if i = 1, The function fib calls with value 1. i.e. fib(1) returns 1 
  • if i = 2, The function fib calls with value 2. i.e. fib(2) returns 1 
  • if i = 3, The function fib calls with value 3. i.e. fib(3) returns fib(2) + fib(1) i.e. it calls the function again. 

So the result is 1 + 1 = 2 

  • if i = 4, The function fib calls with value 4. i.e. fib(4) returns fib(3) + fib(2) i.e. it calls the function again. 

So the result is 2 + 1 = 3 

3. The output will be as follows 1 1 2 3



Discussion

No Comment Found

Related InterviewSolutions