d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Need Java Help.. > Rewrite Using An Dynamic Array
Add Reply New Topic New Poll
Member
Posts: 588
Joined: Apr 29 2009
Gold: 143.76
Oct 29 2012 07:24pm
The code below prints the first 20 numbers of Fibonacci series using an array, I need help rewriting the code using an dynamic array.

public class Fibonacci
{
public static void main(String[])
{
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] );
}
}
}

will offer fg for correct answer..

This post was edited by speter1 on Oct 29 2012 07:45pm
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Oct 29 2012 08:03pm
by "dynamic array" i assume you mean arraylist? just swap it out. use size() instead of referencing i

not sure why you'd wanna use a dynamic array though. if you want to keep n elements, a static array is best. if you only wanna find a single one, then skip the array all together

This post was edited by carteblanche on Oct 29 2012 08:15pm
Member
Posts: 2,775
Joined: May 17 2008
Gold: 410.74
Nov 15 2012 11:01am
Quote (carteblanche @ 30 Oct 2012 04:03)
by "dynamic array" i assume you mean arraylist? just swap it out. use size() instead of referencing i

not sure why you'd wanna use a dynamic array though. if you want to keep n elements, a static array is best. if you only wanna find a single one, then skip the array all together


If you want to store n elements of fibonacci with n as a parameter arraylist is certainly better.
Member
Posts: 4,605
Joined: Sep 15 2011
Gold: 9,464.00
Nov 15 2012 03:59pm
or how about the best of both worlds. new ArrayList(n)

there's really no compelling reason to use static arrays any longer these days, unless you're working with an API that demands it.


also, major thread necro bro.
Member
Posts: 16,218
Joined: Sep 27 2009
Gold: 13.00
Nov 18 2012 03:57pm
Just write ArrayList list = new ArrayList();

It'll be create a new Object instance of ArrayList. ArrayList has 3 constructor, the one who interest you is the previous, because u want a size of n (it should be better to declare a size if u know the size u want, cuz of optimisation and speed). Each time u'll put an Object in your ArrayList, they'll increase the size automatically.

By the way, if u want to suppress element, make sure to also resize the ArrayList.
And u wouldn't need a for anymore, you can work with, but it's not necessary.

This post was edited by Bremen on Nov 18 2012 03:58pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll