Write a C++ program to compute the Fibonacci numbers. In mathematics, the sequen
ID: 3567362 • Letter: W
Question
Write a C++ program to compute the Fibonacci numbers. In mathematics, the sequence of
Fibonacci numbers is defined by the following recurrence relation.
Fn = Fn-1 + Fn-2, where F0 = 0 and F1 = 1
For example, if n = 3, then F3 = F2 + F1 = (F1 + F0) + F1 = 1 + 0 + 1 = 2.
Your program should contain a void function having two parameters, in which the first
parameter (a value parameter) is n passed from the main function to it and the second parameter
(a reference parameter) is the result passed back to the main function. The main function is to
handle user input for n and pass it to the function described above. The main function is also
responsible for displaying the result to the screen. The following show a sample output for the
program.
Enter a nonnegative number: 3
The Fibonacci number for n = 3 is 2
Explanation / Answer
#include <iostream>
using namespace std;
int fib(int num)
{
cout << "Finding the fib of " << num << endl;
if(num == 0)
{
cout << "We have reached the termination case of 0. Returning 0" << endl;
return 0;
}
if(num == 1)
{
cout << "We have reached the termination case of 1. Returning 1" << endl;
return 1;
}
int result = fib(num - 1) + fib(num - 2);
cout << "Fib of " << num << " is " << result << endl;
return result;
}
int main()
{
fib(6);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.