Answer to Question #330705 in C++ for Secret Agent

Question #330705

Here We Go Again

by CodeChum Admin

This one’s probably one of the most popular recursion problems in programming. Your task is to create a recursive function that prints out the the first up to the nth number in the Fibonacci sequence by going through the numbers using recursion.


In case you forgot, here is the definition of a Fibonacci sequence:

  • fib(n) = 1 if n = 1 or n = 2
  • fib(n) = fib(n-1) + fib(n-2) when n > 2

Instructions:

  1. In the code editor, you are provided with an initial code with a main() that asks the user for an integer n, which represents the number of elements in the Fibonacci sequence to be printed out.
  2. In addition, you are also provided with an initial displayFibonacci() function which contains the code to supposedly display the first n elements in the Fibonacci sequence. However, it is not working as expected.
  3. Your task is to find where the error is and fix the displayFibonacci() function.

Input


1. Elements to be printed

Output


Enter·n:·4
1·1·2·3
1
Expert's answer
2022-04-20T03:44:58-0400
#include <iostream>
using namespace std;


void displayFibonacci(int n) {
    int f2 = 0;
    int f1 = 1;
    int f = 1;


    cout << f;
    if (n == 1) {
        cout << endl;
        return;
    }


    for (int i=1; i<n; i++) {
        f = f1 + f2;
        f2 = f1;
        f1 = f;
        cout << " " << f;
    }
    cout << endl;
    return;
}


int main() {
    int n;

    cout<< "Enter n: ";
    cin >> n;

    displayFibonacci(n);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS