meowthecat
meowthecat

Reputation: 51

Printing a particular value from an array

How can I print the value of a Fibonacci function for any particular index, say n, where n is the provided argument value?

1 import java.util.Arrays;
2 
3 public class Fibonacci {
4
5 public static void main(String[] args) {
6   int n = Integer.parseInt(args[0]);
7   if(n<3){
8       return;
9   }else{
10      int[] f = new int[n];
11      f[0] = 1;
12      f[1] = 1;
13      int i= 0;
14      for(i=2; i<f.length; i++){
15          f[i]= f[i-1]+ f[i-2];
16      }
17      System.out.println(f[i]);
18  }
19  
20 }
21
22 }

Upvotes: 1

Views: 61

Answers (4)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

Your code is basically fine, but I tweaked a few things in my response:

public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    if (n < 0) {
        System.out.println("Cannot computer Fib() of a negative number.");
        return(0);
    } else if (n < 3) {
       System.out.println("Fib[" + n + "] = 1");
    } else {
        int[] f = new int[n];
        f[0] = 1;
        f[1] = 1;
        for(int i=2; i < f.length; ++i) {
            f[i] = f[i-1]+ f[i-2];
        }
        System.out.println("Fib[" + n + "] = " + f[n - 1]);
    }
}

Upvotes: 1

Sachin Gupta
Sachin Gupta

Reputation: 8358

You are printing f[i] which will give you ArrayIndexOutOfBoundsException since at that time value of i crosses the boundary of array f.

A simple workaround would be to print array by taking a separate variable like this :

int n = Integer.parseInt(args[0]);
if(n<3){
    return;
}else{
    int[] f = new int[n];
    f[0] = 1;
    f[1] = 1;
    int i= 0;
    for(i=2; i<f.length; i++){
        f[i]= f[i-1]+ f[i-2];
     }

     for (int j=0;j<n;j++){
     System.out.println(f[j]);
    }
}

If you want to print any particular index then you can make one boundary check before printing:

int index=5;
if(index<f.length){
    System.out.println(f[index]);
}

Upvotes: 1

Adrian Shum
Adrian Shum

Reputation: 40036

The problem you have, I believe, is System.out.println(f[i]);

At this spot, i will be equals to length of f[]. If you use i as index, it will be out of bound.

If you are going to print the last value, it should be System.out.println(f[i-1]);

Upvotes: 1

hamed
hamed

Reputation: 8033

I think It's better to have Fibonachi in the recursive way:

public int fib(int n) {
    if (n < 2) {
       return n;
    }
    else {
       return fib(n-1)+fib(n-2);
    }
    System.out.println(n);
}

Upvotes: 0

Related Questions