In this post we will learn fibonacci series in java, fibonacci series program in java using recursion and using all other methods.
Table of Contents
What is Fibonacci Series In Java?
In Fibonacci series, the next number is the sum of previous two numbers.
For example – If 0 and 1 are first two number then Fibonacci series is like –
0,1,1,2,3,5,8,13,21…..
There are different ways to find the Fibonacci series using Java program.
Fibonacci Series in java using for loop
package demopkg; public class FibonacciExample1 { public static void main(String[] args) { int count = 8, n1 = 0, n2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); for (int i = 1; i <= count; ++i) { System.out.print(n1+" "); int sum = n1 + n2; n1 = n2; n2 = sum; } } }
Output: Fibonacci Series of 8 numbers:0 1 1 2 3 5 8 13
Fibonacci series program in java using recursion
package demopkg; public class FibonacciSeriesUsingRecursion { static int n1=0, n2=1, n3; static void CalFibonacci(int count) { if(count > 0) { n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(" "+n3); CalFibonacci(count-1); } } public static void main(String[] args) { int count = 8; System.out.print(n1 +" "+ n2); CalFibonacci(count-2); // Two numbers are already printed in above line. } }
Output: 0 1 1 2 3 5 8 13
Fibonacci series in java using scanner
package demopkg; import java.util.Scanner; public class FibonacciSeriesScanner { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter number for Fibonacci Series:"); int count = sc.nextInt(); int n1 = 0, n2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); for (int i = 1; i <= count; ++i) { System.out.print(n1+" "); int sum = n1 + n2; n1 = n2; n2 = sum; } } }
Output:
Enter number for Fibonacci Series:
12
Fibonacci Series of 12 numbers:0 1 1 2 3 5 8 13 21 34 55 89
Fibonacci Series Program in Java using While Loop
package demopkg; public class FibonacciUsingWhileLoop { public static void main(String[] args) { int count = 10, previousNumber = 0, nextNumber = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); int i=1; while(i <= count) { System.out.print(previousNumber+" "); int sum = previousNumber + nextNumber; previousNumber = nextNumber; nextNumber = sum; i++; } } }
Output: Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34
Fibonacci series in python
nNumber = int(input("How many terms? ")) # first two numbers n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nNumber <= 0: print("Please enter a positive integer") elif nNumber == 1: print("Fibonacci sequence upto", nNumber,":") print(n1) else: print("Fibonacci sequence:") while count < nNumber: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1
Output:
How many terms? 7
Fibonacci sequence:
0 1 1 2 3 5 8
Must Read