A classic coding problem and one that I like to solve first when I’m first learning a new programming language, is an algorithm to print the Fibonacci sequence to the nth term.
0, 1 , 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, …
The terms of the Fibonacci sequence are defined as F1 = 0, F2 = 1, and Fn = Fn-1 + Fn-2 . The algorithm for constructing a finite section of this sequence is easy but interesting which makes it a good first program for a language.
import java.lang.reflect.Array;
import java.util.ArrayList;
public class FibSeq {
public static ArrayList<Integer> fibSeq(int positions){
ArrayList<Integer> fibseq = new ArrayList<>();
fibseq.add(0);
System.out.println(fibseq.get(0));
fibseq.add(1);
System.out.println(fibseq.get(1));
for (int iter = 2; iter < positions; iter++){
fibseq.add(fibseq.get(iter - 2) + fibseq.get(iter - 1));
System.out.println(fibseq.get(iter));
}
return fibseq;
}
}
There are many different ways to solve this problem, this is my solution and you can find it on my Github.