Fibonacci series is a special type of series in which the next number is the sum of the previous two numbers. For example, 1 1 2 3 5 8 13 21…. up to a given number.
Solution #1 : Using Recursion
FibonacciSeriesWithRecursion.java
package com.javacodepoint.programs;
import java.util.Scanner;
public class FibonacciSeriesWithRecursion {
// initiating first two numbers of the Fibonacci series
static int number1 = 0;
static int number2 = 1;
public static void main(String[] args) {
// Taking input from the user to print Fibonacci series up to how many numbers
System.out.println("Enter number up to which Fibonacci series to print:");
// Reading user input using Scanner object
int upto = new Scanner(System.in).nextInt();
// Printing first two numbers
System.out.print(number1 + " " + number2);
// Calling recursive function by decreasing 2 because two numbers are already printed
printFibonacci(upto - 2);
}
/*
* Recursive function
*/
public static void printFibonacci(int count) {
if (count > 0) {
int nextNumber = number1 + number2;
number1 = number2;
number2 = nextNumber;
System.out.print(" " + nextNumber);
// Call the recursive function again
printFibonacci(count - 1);
}
}
}
OUTPUT:
Enter number up to which Fibonacci series to print:
12
0 1 1 2 3 5 8 13 21 34 55 89
Solution #2 : Without Using Recursion
FibonacciSeries.java
package com.javacodepoint.programs;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
// Taking input from the user to print Fibonacci series up to how many numbers
System.out.println("Enter number up to which Fibonacci series to print:");
// Reading user input using Scanner object
int upto = new Scanner(System.in).nextInt();
// Initiating first two numbers of the Fibonacci series
int number1 = 0;
int number2 = 1;
// Printing first two numbers
System.out.print(number1 + " " + number2);
// Start the loop from 3 because first two numbers are already printed
for (int i = 3; i <= upto; i++) {
int nextNumber = number1 + number2;
System.out.print(" " + nextNumber);
number1 = number2;
number2 = nextNumber;
}
}
}
OUTPUT:
Enter number up to which Fibonacci series to print:
10
0 1 1 2 3 5 8 13 21 34