Amazon Affiliate

Thursday 9 August 2012

PROGRAM FOR FIBONACCI SERIES USING RECURSION IN JAVA...


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));
    }
}

5 comments:

  1. can u please explain the logic of fib(n-1) + fib(n-2) how this part works

    ReplyDelete
  2. see, 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.
    next 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

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. thanks for explaining Rupuneet Kaur

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete