Friday, April 11, 2008

Fibonacci

The Fibonacci series consists of a series of numbers where the next number is calculated by adding the previous two. The first two numbers in the series are 1. That is, the series starts out:

1
1
2
3
5
8
13

Write a function which takes as input an integer x an returns an array of integers filled with fibonacci numbers in order.

First declare the array then fill it with the appropriate numbers by iterating from the smallest to the biggest.


public class Fibonacci {

public static int[] getSeries(int x){
int[] result = new int[x];
result[0]= 1;
result[1]= 1;
for (int i=2; i < x; i++){
result[i] = result[i-1] + result[i-2];
}
return result;
}

public static void main (String [] args){
int[] fib = Fibonacci.getSeries(20);
for (int i : fib){
System.out.println(i);
}
}
}


1 comment:

javin paul said...

I just found your blog after writing my own list of programming interview questions ,I must say you have got awesome blog , please share different approaches of solving problems and tips as well.

Javin
Top 20 Core Java Interview question

ShareThis