# Fibonacci sequence using Dynamic Arrays

Printable View

• 02-12-2014, 09:01 PM
MylesPollie
Fibonacci sequence using Dynamic Arrays
public class Fibonacci
{
public static void main(String[] args)
{
int[] numbers;
numbers = new int[20];
numbers[0] = 0;
numbers[1] = 1;
System.out.println("\nFibonacci series:\n");
System.out.println(numbers[0]);
for (int i=2;i<20;i++)
{
numbers[i]=numbers[i-2]+numbers[i-1];
System.out.println(numbers[i]);
}
}
}

I wrote this program for my Java class to print out the first 20 numbers of the Fibonacci series. My assignment then tells me to Rewrite your program using dynamic array. I'm not sure how to do this. I would really appreciate some help. Thanks!
• 02-12-2014, 09:03 PM
KevinWorkman
Re: Fibonacci sequence using Dynamic Arrays
Do you know what a dynamic array is? If not, there's your starting point! If so, what specifically about this is giving you trouble?
• 02-12-2014, 09:06 PM
MylesPollie
Re: Fibonacci sequence using Dynamic Arrays
I understand that a dynamic array allows you to alter the size of the array during the execution of the program, but I don't understand how to apply it in the program.
• 02-17-2014, 03:17 PM
KevinWorkman
Re: Fibonacci sequence using Dynamic Arrays
The question is, what happens if you want to go beyond the 20th number in the series? With your existing code you would be stuck because your array only has 20 indexes. The answer to that problem is to use a dynamic array that grows when you reach its capacity. What have you tried?
• 02-17-2014, 03:45 PM
gimbal2
Re: Fibonacci sequence using Dynamic Arrays
Quote:

Originally Posted by MylesPollie
I understand that a dynamic array allows you to alter the size of the array during the execution of the program, but I don't understand how to apply it in the program.

There is no such thing as a dynamic array; an array is static sized in Java. You have two basic options;

1. create a new array that is larger than the first and copy the original array to the new array
2. use a class which can do this for you

The assignment is very vague, but I think you have to do #1. You will have to confirm that with the person who gave you this assignment.
• 02-17-2014, 05:05 PM
KevinWorkman
Re: Fibonacci sequence using Dynamic Arrays
Right, I should have clarified that when I said that you'd have to use a dynamic array, what I meant was you'd have to create a data structure that *acts* like a dynamically sized array.
• 02-17-2014, 05:26 PM
gimbal2
Re: Fibonacci sequence using Dynamic Arrays
And now the OP needs to ask what he really needs to do, its simply not clear which option is the correct one.