Thursday, March 20, 2014

Fibonacci Series in Java


Q. Print Fibonacci series in Java.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
public class FibonacciSeries {
  
 public static void main(String[] args) {
  int sum = 0;
  //how many numbers to print
  for(int i=0, j=1; i<=10; i++){
   if(i==0){
    //for printing first number which is 0
    System.out.print(0 + ", ");
   }
   else{
    //j has last 'sum', and sum now stores latest added value
    //while the control enters again, j gets latest 'sum' value before
    //new sum is calculated and printed again
    sum = j + (j=sum);
    System.out.print(sum + ", ");
   }
  }
 }
}