Need help with a Recursion Code.

*/ I’ve been trying to write a recursion code with 2 arguments in Java but this is as far as I got. Could you tell me if I’m on the right path? (Fib) = Fibonacci Is there a better way to write this code with a explanation? */

public static void main (String[] args)
{
int n1 = 0;
int n2 = 1;
System.out.println(“n1=”+n1);
fib(n1, n2);
}

public static void fib(int n1, int n2)
{
System.out.println(“n2=”+n2);
}

You probably wanted to have it call itself, but that would give you an infinite loop. If that’s not a problem; you’ll have to assess what you want to do each step.

public static void main (String[] args)
{
int n1 = 0, n2 = 1, n3 = 0;
System.out.println("n1 = " +n1);
fib(n1, n2);
}

public static void fib(int n1, int n2)
{
System.out.println("n2 = " +n2);
n3 = n2;
n2 = n1 + n2;
n1 = n3;
fib(n1, n2);
}

your fib(n1, n2) code is something that should do each step so you call it again and again in itself;
Adjust values to what it needs to be for the next iteration and call itself. Rinse and repeat.

1 Like

#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fib(n-1)+fib(n-2);
}
int main()
{
int n;
cin>>n;
cout<<fib(n);
return 0;
}
C++ Version.

1 Like