vendredi 11 juin 2021

Need help in converting this simple for loop into another function that's being called recursively

How to integrate the for loop with the existing function or write a new function that runs from 0 to n where n is the input from user?

//Write a program in C or C++ to Print Fibonacci Series using recursion.
#include <stdio.h>

int fib(int n)
{
    if (n == 0 || n == 1)
        return n;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main()
{
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");
    for (int i = 0; i < n; i++)
    {
        printf("%d", fib(i))
    }
    return 0;
}

My try:

//Write a program in C or C++ to Print Fibonacci Series using recursion.
#include <stdio.h>

int fib(int n)
{
    if (n == 0 || n == 1)
        return n;
    else
        return fib(n - 1) + fib(n - 2);
}
void rec(int n)
{
    if(n>0)
        rec(n-1);
    else
        printf("%d", fib(n));
}

int main()
{
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");
    // for (int i = 0; i < n; i++)
    // {
    //     printf("%d", fib(i))
    // }
    rec(n);
    return 0;
}

This took my input correctly but output was 0.

I know I can print the Fibonacci series in a single function using static int or global variables but I am not allowed to use them. So is there any other way to print the Fibonacci series using recursion in a single function? If not, that's fine, 2 different recursive functions also works.

The code to print fibonacci series using recursion and static int variables is:

void fib(int n)
{
    static int n1 = 0, n2 = 1, n3;
    if (n > 0)
    {
        n3 = n1 + n2;
        n1 = n2;
        n2 = n3;
        printf("%d ", n3);
        fib(n - 1);
    }
}
int main()
{
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");
    printf("0 1 ");
    fib(n - 2);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire