
Fibonacci Series is one of the most famous program when you start programming in Computer Science School or College. This program help you understand how to think logically and the art of building code logic.
✏️ What is Fibonacci Series or Fibonacci number?
In Math - Fibonacci is a sequence of numbers such that each number is a sum of its previous two number.
Formula: Fn = Fn-1 + Fn-2
Example: 0 1 1 2 3 5 8 13 21 34 . . . .
Ok, so now that we know the formula of a Fibonacci sequence lets try to build the pseudo logic before we try to achieve this programmatically.
Pseudo Logic:- Lets take the first number of the series as 0 and call it variable n0,
- Lets take the second number of the series as 1 and call it as variable n1,
- Lets create variable n that stores the current Fibonacci number ,
- Print out the first variable n0 - this is the 1st Fibonacci number of the series,
- Print out the second variable n1 - this is the 1st Fibonacci number of the series,
- Now lets add a loop that iterates from 1 to 50,
- Inside the loop: let n = n0 + n1,
- Inside the loop: let n0 = n1,
- Inside the loop: let n1 = n
- Print out the value of n
Example 1: Fibonacci using Java For Loop
Let's try and implement the above logic in Java code. I have mentions step numbers at each line as comments so that you can co-relate with the pseudo logic.
/**
*
* This is a Java Program
* that demonstrates how
* to display Fibonacci
* series or number or
* sequence.
*
*/
public class Fibonacci {
public static void main(String... args) {
//Note: Use long not int as numbers would
//Go out of range
long n0 = 0; //Step 1: 1st number
long n1 = 1; //Step 2: 2nd number
long n = 0; //Step 3: to hold sum of previous two numbers
//Step 4 & 5: Just do a print and display first two numbers
System.out.print(n0 +" " + n1 + " ");
//Step 6: We want to display 50 Fibonacci numbers
for(int i=0; I<=47; i++) {
n = n0+n1; //Step 7
n0 = n1; //Step 8
n1 = n; //Step 9
System.out.print(n +" "); //Step 10
}
}
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049
⛔️ A word of caution: Do not use the variable types as int (integers) as they would go out of range and you would see invalid outputs - negative numbers in the output as shown below:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 -1323752223 512559680 -811192543
Example 2: Fibonacci Series using While loop
Let's try to write the same above code using a while loop instead of a for loop, we would need to add a new variable counter to keep the count to know when to come out of the while loop,
/**
* Fibonacci series using
* Java While Loop
*
*/
public class Fibonacci {
public static void main(String... args) {
long n0 = 0;
long n1 = 1;
long n = 0;
int counter = 0; //to break out of while loop
System.out.print(n0 +" " + n1 + " ");
while(counter <= 47) {
n = n0+n1;
n0 = n1;
n1 = n;
System.out.print(n +" ");
counter++;
}
}
}
Example 3: Fibonacci using main argument
Let's enhance the code further to take in user input from java main argument based on the number inputted, we will display the Fibonacci. Let's also check that the provided input is less than or equal to 50. Note the input will be of type String so we would need to convert it to an int using Integer.parseInt() method.
/**
* Fibonacci series using
* user input using
* main argument
*
*/
public class Fibonacci {
public static void main(String... args) throws Exception {
int counter = Integer.parseInt(args[0]);
if(counter > 50) {
throw new Exception("Error: Input should be not more than 50");
}
System.out.println("Inputted value: " + counter);
long n0 = 0;
long n1 = 1;
long n = 0;
System.out.print(n0 +" " + n1 + " ");
while(counter >= 0) {
n = n0+n1;
n0 = n1;
n1 = n;
System.out.print(n +" ");
counter--;
}
}
}
Example 4: Fibonacci series using Scanner
This could be one of the question you may be asked in your pogromming exam - read a number using Java Scanner class and then print the Fibonacci series. Make sure to import import java.util.Scanner
import java.util.Scanner;
/**
* Fibonacci series using
* user input using
* Java Scanner class
*
*/
public class Fibonacci {
public static void main(String... args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int counter = Integer.parseInt(in.nextLine());
if(counter > 50) {
throw new Exception("Error: Input should be not more than 50");
}
System.out.println("Inputted value: " + counter);
long n0 = 0;
long n1 = 1;
long n = 0;
System.out.print(n0 +" " + n1 + " ");
while(counter >= 0) {
n = n0+n1;
n0 = n1;
n1 = n;
System.out.print(n +" ");
counter--;
}
}
}
Output:
Enter a number: 5
Inputted value: 5
0 1 1 2 3 5 8 13
Example 5: Fibonacci Series using recursion function
Ah! This is yet another variation that is asked in exams! This program will print the Fibonacci number based on the input provided.
/**
* Fibonacci number
* using Recursion
*
*/
public class Fibonacci {
public static void main(String... args) throws Exception {
System.out.println(fibonacciRecursion(6));
}
static int fibonacciRecursion(int sequenceNumber) {
if (sequenceNumber <= 1) {
return sequenceNumber;
}
return fibonacciRecursion(sequenceNumber - 1) + fibonacciRecursion(sequenceNumber - 2);
}
}
- CRUD operations in Spring Boot + JDBC
- Java Check Leap Year - Programs with Code Examples
- [fix] Java JDBC ConnectException: Connection refused
- How to add hours and minutes to Java Instant
- Java Program: Random Number Generator
- Java: The value of the local variable string is not used
- How to get list of all Java versions installed on macOS
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Java + Spring JDBC Template + Gradle Example
- Convert String to LocalDate in Java
- Remove Trailing zeros BigDecimal Java
- Java 8 Predicate Functional Interface isEqual() Method Example
- How to Hardcode Date in Java with Examples
- Java 8: Predicate negate() default Function Example
- Java: Collect Stream as ArrayList or LinkedList
- The Motivation Behind Generics in Java Programming
- How to Add/Subtract Days to the Current Date in Java
- Error: Can not find the tag library descriptor for
- Setting up JUnit 5 dependency with Maven Example
- Run Java Code Every Second
- How to create a tar.gz file using Java
- [Fix] java: integer number too large compilation error
- Java 8: Find the Max value in a List
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- Convert Java Array to ArrayList Code Example
- Changing Android Intent Tittle using java code - Android
- Make Notepad++ the default App for .txt file extensions - NotepadPlusPlus
- Enable macOS Stage Manager - MacOS
- Java: Reference List of Time Zones and GMT/UTC Offset - Java
- [fix] SharePoint: We only support embedding content from secure websites - SharePoint
- Notepad++ : Cannot load 64 or 32bit plugin Error. - NotepadPlusPlus
- SharePoint List excel import - This table exceeds the maximum number of supported rows - SharePoint
- Update Powershell Using Command Line - Powershell