In this post we'll see a Java program to display Fibonacci series.
Fibonacci series is a series of natural numbers where next number is equivalent to the sum of previous two numbers i.e. fn = fn-1 + fn-2.
The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, and each subsequent number is the sum of the previous two numbers. Java programs in this post we'll display the Fibonacci series as - 0 1 1 2 3 5 8 ...
Fibonacci series Java program can be written either using recursive logic or iterative logic. In this post we'll see Java programs for both.
Java program to display Fibonacci series using recursion
If you are using recursive logic then you have to call the same method with both n-1 and n-2 where n is the passed number. Since the first two numbers in the series are 0 and 1 so check for these two numbers as exit condition in the recursive method. So n=0 and n=1 are the base cases for recursive program.
import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); //user input System.out.println("Enter how many numbers are needed in Fibonacci series: "); int num = input.nextInt(); for(int i = 1; i <= num; i++){ System.out.print(printFibonacci(i) + " "); } input.close(); } private static int printFibonacci(int num){ //For first two numbers if(num == 0){ return 0; } if(num == 1){ return 1; } return printFibonacci(num - 1) + printFibonacci(num - 2); } }
Output
Enter how many numbers are needed in Fibonacci series: 12 0 1 1 2 3 5 8 13 21 34 55 89 144
Java program to display Fibonacci series using iteration
In Fibonacci series next number is the sum of previous two numbers. Iterative program uses the same logic by taking three variables, in a for loop you first print the number and then move one step forward by assigning the previous two numbers to two of the variables and assigning the sum of these two variables to the third variable.
import java.util.Scanner; public class FibonacciItr { public static void main(String[] args) { Scanner input = new Scanner(System.in); //user input System.out.println("Enter how many numbers are needed in Fibonacci series: "); int num = input.nextInt(); printFibonacci(num); input.close(); } private static void printFibonacci(int num){ int num1, num3 = 0; int num2 = 1; for(int i = 0; i <=num; i++){ System.out.print(num3+" "); num1 = num2; num2 = num3; num3 = num1 + num2; } } }
Output
Enter how many numbers are needed in Fibonacci series: 14 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
That's all for this topic Fibonacci Series Program in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment