Java – Fibonacci Sequence in Array

email me

Compiled and tested here: http://www.browxy.com/

With Initialized Array

import java.util.Scanner;

public class FibSeries {

public static void main (String [] args){

// fib sequence
int [] x = {0,1,1,2,3,5,6,13,21,34,55};

int i;

for (i=0; i<x.length; i++){

// output
System.out.print(x[i] + " ");

}
}
}

// screen output
// 0 1 1 2 3 5 8 13 21 34 55

With For Loop

import java.util.Scanner;

public class FibSeries {

public static int fibonacci(int n) {
int x = 0;
int y = 1;

// compute fib sequence
for (int i = 0; i < n; i++) {
int z = x;
x = y;
y = z + y;
}
return x;
}

public static void main(String[] args) {

for (int i = 0; i < 11; i++) {
// output
System.out.print(fibonacci(i) + " ");
}
}
}

// screen output
// 0 1 1 2 3 5 8 13 21 34 55