In this post, we will learn, How to write a program to display Fibonacci Series based on given user input.
Before moving to the programming part, Let's try to understand, What is Fibonacci Series?
Fibonacci Series- This is the number of sequences in which the series starts with 0,1 and the next number is found by adding up the two numbers before it.
Ex:- 0,1,1,2,3,5,8,13,21.........
Code-
public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + ",");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
Output-
First 10 terms: 0,1,1,2,3,5,8,13,21,34,
Print Fibonacci Series Using Recursive Function
public class Fibonacci {
static int n1 = 0, n2 = 1, n3 = 0;
static void printFibonacci(int count) {
if (count > 0) {
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" " + n3);
printFibonacci(count - 1);
}
}
public static void main(String args[]) {
int count = 10;
System.out.print(n1 + " " + n2);//printing 0 and 1
printFibonacci(count - 2);//n-2 because 2 numbers are already printed
}
}
Explanations-
The program defines a static method called printFibonacci() which takes an integer argument representing the number of terms to be printed. The method uses a base case of count > 0 to stop the recursion when the specified number of terms have been printed.
In each recursive call, the next term in the series (n3) is computed as the sum of the previous two terms (n1 + n2) and the value is printed out. Then the values of n1 and n2 are updated for the next recursive call.
The main method sets the number of terms to be printed to 10 and prints the first two terms (0 and 1) before calling the printFibonacci() method.
Hope this program helpful for you, Please put your valuable comment and share with your friends-------
Post a Comment