Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
224 views
in Functions by (30.3k points)
closed by

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?

for (int i=1; i<5; i++) 

cout<<fib(i)<<'\t';

1 Answer

+1 vote
by (30.5k points)
selected by
 
Best 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

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...