1

I am learning Java and I have this code from the internet and running it in Eclipse:

public class FibonacciArray { public static void main (String [] args) {

    long fib [] = new long [21];    
    int i;

    fib[0] = 0;
    fib[1] = 1;

for(i = 2; i < 21; i++)
        fib[i] = fib[i-1] + fib[i-2];

for (i = 0; i < 21; i++)
        System.out.println(fib[i]);
    }
}

From what I understand the first loop starts at 2 then shouldn't it store 2-1 + 2 -2 into fib[i]? which is correct at the index 2 this will be 1.

When the index is 3 however this scenario doesn't work as 3-1 + 3- 2 is 3 and the value at this index is 2.

Also does the second for loop just print the numbers created above the first for loop and the first for loop?

Thanks

Edit: the other question which is supposedly a duplicate used recursion so I understood how the value got to what was needed in the end. This uses loops and the first value passed is 2 so how can it use the same logic as the other one or the same question?

John
  • 15
  • 3
  • 3 hours ago you asked a very similar question! – Rahul Tripathi Aug 16 '14 at 17:11
  • @R.T this one is different though – John Aug 16 '14 at 17:16
  • @R.T the other one used recursion so I understood how the value got to what was needed in the end. This uses loops and the first value passed is 2 so how can it use the same logic as the other one? – John Aug 16 '14 at 17:18
  • You should perhaps study how to convert a recursive function to a for loop (easily google-able) instead of asking a separate question with the same fundamental response. The only real difference, note, is that the for loop knows how many iterations it has and needs to start at the end, doing the same work in a given iteration that a recursive call did. – Nathaniel Ford Aug 16 '14 at 17:48
  • @NathanielFord Yes your right I should have studied how to convert a recursive function to a for loop. I had that idea that the loop starts at the end as it knows how many iterations it has and worked the same way backwards. Thanks for your help. – John Aug 16 '14 at 17:56

0 Answers0