Java program to print fibonacci series.



A fibonacci series is one in which the next term is the sum of previous two terms
Example. 0 1 1 2 3 5 8……



import java.util.Scanner;
public class Fibonacci 
{
 public static void main(String args[]) {
  func(10);
 }
 static void func(int n) {
  int a = 0, b = 1, c = 0, i;
  System.out.print(a + " , " + b);
  for (i = 3; i <= n; i++) {
   c = a + b;
   System.out.print(", " + c);
   a = b;
   b = c;
  }
 }
}

Output:

0 , 1, 1, 2, 3, 5, 8, 13, 21, 34
BUILD SUCCESSFUL (total time: 0 seconds)


No comments:

Post a Comment