106k views
4 votes
The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, has as its first 2 values, 0 and 1; each successive value if then calculated as the sum of the previous two values. The first element in the series is the 0'th element, thus the value 8 is element 6 of the series. The n'th element of the series, written as fib(n), is thus defined as: n if n = 0 or n = 1 fib(n-1) + fib(n-2) Write the int-valued method fib, that takes a single int parameter (say n), and recursively calculates and then returns the n'th element of the Fibonacci series.

1 Answer

2 votes

Answer:

// Code in C++.

// headers

#include <bits/stdc++.h>

using namespace std;

// recursive function to find nth term of Fibonacci series

int fib(int num)

// driver function

int main()

{

// variables

int num, term;

cout << "Enter the position value : ";

// read the value of num

cin >> num;

// call the function

term = fib(num);

// print the nth term

cout <<"The "<<num<< "th Fibonacci number is: " <<term<<endl;

return 0;

}

Step-by-step explanation:

Read the value of term number from user and assign it to variable "num".Then call the recursive function fib() with parameter "num".In this function, if num=1 or num=0 (base case for recursive call) then function will return the value of num. otherwise it will recursively call itself and find the nth term of the Fibonacci series.

Output:

Enter the position value : 6

The 6th Fibonacci number is: 8

User Toan Nguyen
by
5.3k points