Thread: Fibonacci sequence using Dynamic Arrays

1. Member
Join Date
Feb 2014
Posts
6
Rep Power
0

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!

2. 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?

3. Member
Join Date
Feb 2014
Posts
6
Rep Power
0

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.

4. 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?

5. Just a guy
Join Date
Jun 2013
Location
Netherlands
Posts
5,114
Rep Power
9

Re: Fibonacci sequence using Dynamic Arrays

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.

6. 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.

7. Just a guy
Join Date
Jun 2013
Location
Netherlands
Posts
5,114
Rep Power
9

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.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•