In this example I’m going to show you how to write a program to print Fibonacci series in Java.
The same Fibonacci programme is written in other languages such as C and JavaScript, search “fibonacci” in the search field to find those. Soon I will be writing in all other programming languages too.
If you already don’t have knowledge about Fibonacci, here is a simple explanation,
0, 1, 1, 2, 3, 5, 8…
0,1 -> 0 +1 =1 ( 1 is the next number)
0,1,2 -> 1+1 = 2 (2 is the next number)
0,1,2 -> 1+2 = 3
0,1,2,3 -> 2+3 = 5
So basically Fibonacci series is finding the next number by adding the previous two numbers.
Here is the Java Program to print Fibonacci series:
import java.util.*;
public class fibonacci {
public static void main(String[] args) {
//define the variable
int limit, next_num, first_num = 0, second_num = 1;
Scanner in = new Scanner(System.in);
System.out.print("Enter the limit: ");
limit = in.nextInt();
//check the input if the value is greater than 0
if(limit > 0){
System.out.println(first_num);
}else{
System.out.println("Value should be greater than 0");
}
//check if input is 1
if(limit > 1){
System.out.println(second_num);
}
//if the input is > 2 then do then print fibonacci
while(limit > 2)
{
//add the first value and second to get the next value
next_num = first_num + second_num;
//assign second value to first
//next value to second
//to find the next series
first_num = second_num;
second_num = next_num;
//print the next value
System.out.println(next_num);
//decrement the limit by one
limit--;
}
}
}
The output of the program will be:
Enter the limit: 6
0
1
1
2
3
5
Keep learning, update your knowledge daily!