import java.util.Scanner;
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number :");
int num = s.nextInt();
for (int i = 1; i <= num; i++)
System.out.println(i + ": " + fib(i));
}
}
can u please explain the logic of fib(n-1) + fib(n-2) how this part works
ReplyDeletesee, it begins with i=1, so it will calculate value for fib(1), now as n=1 which is (n<=1) is true, so it returns 1.
ReplyDeletenext tym wen i=2, value for fib(2) is calc. that will return fib(1)+fib(0);
fib (0)--> 0; fib(1){as calc above}--> 1;
fib(2)= 1+0=1;
i=3; fib(3)= fib 2+ fib 1
here also previously found values are used to calc it an so it flows
This comment has been removed by a blog administrator.
ReplyDeletethanks for explaining Rupuneet Kaur
ReplyDeleteThis comment has been removed by the author.
ReplyDelete