How to print Fibonacci series in java

The Fibonacci sequence/series is a series where the next term is the sum of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21.

Java code for Fibonacci series

 

import java.util.Scanner;
public class fibonacci_series
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.err.print(“Enter till which Fibonacci series is to be printed :”);
int n=s.nextInt(),a=0,b=1;
System.out.println(n+” numbers in Fibonacci series are :”);
System.out.print(a+”, “+b);
for(int i=3;i<=n;i++)
{
int c=a+b;
System.out.print(“, “+c);
a=b;
b=c;
}
System.out.println(“”);
}
}

 

Output -:

Leave a Reply