In this tutorial you will learn about the Java Program to Generate Fibonacci Series and its application with practical example.
Java Program to Generate Fibonacci Series
In this tutorial, we will learn to create a Java program that will Generate Fibonacci Series using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- Conditional Statements in Java programming.
- Arithmetic operations in Java Programming.
Program to generate the Fibonacci series:-
In this program, we will, first, declare the variables for the program. Then we will assign the values to the variables. Now we will use the user-defined function to generate the Fibonacci series to the endpoint using the arithmetic expression. At last, we will print the output Fibonacci series to the user.
With the help of this program, we can Generate Fibonacci Series.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the required variables for the program. 2. Taking the input number from the user. 3. Passing that number to a user defined function. 4. Generating the Fibonacci series up to an ending point. 5. Printing the Fibonacci Series to the user. 6. End the program. |
Program to Generate Fibonacci Series:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//Java Program to Generate Fibonacci Series class Fibo{//main Class of the program. //Declaring the required variables for the program static int n1=0,n2=1,n3=0; //User defined function to create the Fibonacci series. static void printFibo(int flaag){ if(flaag>0){ //Creating the Series using arithmetic operations. n3 = n1 + n2; n1 = n2; n2 = n3; //Printing the series to the user System.out.print(" "+n3); printFibo(flaag-1); } } public static void main(String args[]){ //Body of main function //Declaring the length of the series. int flaag=10; System.out.print(n1+" "+n2);//printing 0 and 1 printFibo(flaag-2);//n-2 because 2 numbers are already printed } } |
Output:-
In the above program, we have first initialized the required variable.
![](https://www.w3adda.com/wp-content/uploads/2021/06/1-18.jpg)
- flag = it will hold the integer value for the length of the series.
Input message for the user for the integer value.
![](https://www.w3adda.com/wp-content/uploads/2021/06/2-18.jpg)
Program Logic Code.
![](https://www.w3adda.com/wp-content/uploads/2021/06/3-19.jpg)
Printing output Fibonacci Series.