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);
}
}
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- [Fix] zsh: command not found: awscli [Mac Terminal] - AWS
- Download Google Chrome setup exe file using PowerShell - Powershell
- New-SPLogFile PowerShell - create new SharePoint log file - SharePoint
- Two Ways to Extract rar (*.rar) files on Mac - MacOS
- Check version of pip package installer for Python - Python
- SharePoint - Use Today's Date Time in list view filter and calculated column - SharePoint
- Notepad++ Save Failed - Please check if this file is opened in another program. - NotepadPlusPlus
- How to fix Microsoft Windows 10 update error 80070020 - Microsoft