Answer to Question #334514 in C for Nika

Question #334514

3. 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.
1
Expert's answer
2022-04-27T13:24:11-0400
#include <stdio.h>

int displayFibonacci(int n)
{
    if ((n == 1) || (n == 2))
        return 1;

    return displayFibonacci(n-1) + displayFibonacci(n-2);
}

int main()
{
    int n;
    printf("Enter n: ");
    scanf("%d", &n);
    printf("\nFibonacci sequence:\n");
    for(int i=1; i<=n; i++)
        printf("%d ", displayFibonacci(i));

}

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