In this tutorial, you’ll learn fibonacci series in Java using for loops.
We’ll be covering the following topics in this tutorial:
What is Fibonacci Series in Java
Fibonacci series numbers are in the following Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…, The first two number in Fibonacci series are 0 and 1, and each subsequent next number is the sum of the previous two Numbers.
Here We’ll write two fibonacci series programs
• Fibonacci Series without using recursion
• Fibonacci Series using recursion
Algorithm for Fibonacci Series
step 1: Set a = 0,b = 1,c = 0 step 2: Read size step 3: Print a,b step 4: Repeat through step-8 until (c < = size) step 5: c = a + b step 6: If (c <= size) then print c step 7: Set a = b step 8: Set b = c step 9: Exit
Fibonacci Series without using Recursion
import java.util.Scanner; public class FibonacciSeries { public static void main(String args[]) { int a = 0,b = 1,c = 0,size; Scanner s=new Scanner(System.in); System.out.print("Enter a range : "); size=s.nextInt(); System.out.print("\n"); System.out.print(a+","+b+","); while(c <= size) { c = a+b; if(c <= size) System.out.print(c+","); a = b; b = c; } } }
Fibonacci Series using Recursion
public class FibonacciSeriesinJava { static int a= 0,b = 1,c = 0; static void FibonacciSeries(int count){ if(count>0){ c = a + b; a = b; b = c; System.out.print(" "+c); FibonacciSeries(count-1); } } public static void main(String args[]){ int count=15; System.out.print(a+" "+b);//printing 0 and 1 FibonacciSeries(count-2);//n-2 because 2 numbers are already printed } }