0

So given this.

//Fibonacci Series using Recursion
class fibonacci
{
    static int fib(int n)
    {
    if (n <= 1)
    return n;
    return fib(n-1) + fib(n-2);
    }

    public static void main (String args[])
    {
    int n = 10;
    System.out.println(fib(n));
    }
}

How could I transform it so it takes an index as a parameter and returns the given Fibonacci number at that index? So say I put in index = 5 and it should return 8.

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • 2
    so what do you think? why is `n` 10? what would happen if you changed it to 5? – Scary Wombat Jun 27 '18 at 01:32
  • @user9992009 Fibonacci sequence is a constant sequence and doesn't change with value n, so in your current program of fibonacci series is providing you number at n index – Aman Chhabra Jun 27 '18 at 01:39

2 Answers2

0
static int fib(int index)
{
       int counter = 0;
       int current = 0;
       int previous = 0;
       int temp = 0;
       while(counter < index)
       {
              temp = previous;
              previous = current;
              current += temp;
              counter++;
       }
       return current;
}

If it does not have to be recursive, then I think this might work. Haven't tested it but tried to answer your question

Narutachi
  • 1
  • 2
0
int main(){
int index, temp1 = 0, temp2 = 1, value_at_index = 0;
    printf("Enter index: ");
    scanf("%d",&index);
    if(index==1){
       printf("Fib value at index 1 = 1");
    }
    else{
        for (int i = 2; i <= index; ++i){
              value_at_index = temp1 + temp2;
              temp1 = temp2;
              temp2 = value_at_index;
        }
       printf("Fib value at index %d = ", index);
       printf("%d\n", value_at_index);
       return 0;
    }
}