Monday, December 31, 2018

Java program for fibonacci series for n elements




    package example;

import java.util.ArrayList;
import java.util.List;

public class Fibonacci {

public static void main(String[] args) {
int n =10;
int t1=0, t2=1;
int sum;

List<Integer> l = new ArrayList<>();
l.add(t1);l.add(t2);
for(int i = 1; i<(n - 1); i++)
{
  sum = t1 + t2;
  l.add(sum);
  t1 = t2;
  t2 = sum;

}
       System.out.println(l);
}

}

Output:  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

No comments:

Post a Comment