1. Home

Step by Step Java Tutorial Concepts - From Beginner to Pro

Learn Java programming from basics to advanced concepts with our comprehensive tutorials. Start from scratch and elevate your skills to expert level.

• 192 Lessons
• 32 Hours
179.Â

# Fibonacci Series in Java

Updated on 19/07/20245,339 Views

The Fibonacci series in Java is a set of numbers where every number is the sum of the two numbers before it. The series starts from 0, and the following number is 1. These are constant. After this, all consequent numbers in the series are obtained by adding the two preceding them. The resultant set of numbers is known as the Fibonacci series in Javascript and can be continued forever.

The recursive approach, dynamic programming methods like memoization and tabulation, and an iterative loop approach are some approaches to constructing this series in Java.

We may use a loop or recursion in Java to construct the Fibonacci sequence. From there, we can perform functions like printing the first n ( where n= real number) Fibonacci numbers from a certain point or even functions to find the sum of first 10 Fibonacci series in Java.

This tutorial will discuss more about the Fibonacci series.

## What is Fibonacci Series (Top-Down Approach and Bottom-Up Approach)

Each number in the Fibonacci series is the sum of the two numbers that came before it. The first two numbers in the sequence are 0 and 1; each subsequent number is created by adding the first two.

The series is represented by the following numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... The syntax changes with respect to the programming interface. For example, the Fibonacci series in C is different from the Fibonacci series in Python. However, the logic remains the same as it is a mathematical concept.

### 1. Top-down approach:

A recursive top-down method is one technique to produce the Fibonacci sequence. To compute the remaining numbers using this method, we first execute the function recursively in the base case, where the first two integers are 0 and 1.

Here is an example of this approach:

`public static int fibonacci(int n) {Â  Â  if (n <= 1) {Â  Â  Â  Â  return n;Â  Â  }Â  Â  return fibonacci(n - 1) + fibonacci(n - 2);}`

### 2. Bottom-up approach:

The following Java code demonstrates the bottom-up approach for producing the Fibonacci sequence.

In this method, we first consider the simple scenario where the first two numbers are 0 and 1, and then we loop over all the other numbers, computing them one at a time and storing them in an array. The n-th element of the array is then returned.

Here is an example of this approach:

`public static int fibonacci(int n) {Â  Â  if (n <= 1) {Â  Â  Â  Â  return n;Â  Â  }Â  Â  int[] fib = new int[n + 1];Â  Â  fib[0] = 0;Â  Â  fib[1] = 1;Â  Â  for (int i = 2; i <= n; i++) {Â  Â  Â  Â  fib[i] = fib[i - 1] + fib[i - 2];Â  Â  }Â  Â  return fib[n];}`

## Ways to Print Fibonacci Series in Java

The Fibonacci sequence may be printed in Java in a variety of ways. Here are two such methods:

### The bottom-up approach in Java:

Starting with the basic situation when the initial two numbers are 0 and 1, the bottom-up method for creating the Fibonacci sequence in Java iteratively calculates each succeeding number. Here is an illustration of a Java bottom-up approach:

### How do we approach it?

This method involves first determining if n is less than or equal to 1, and if it is, we return n since the first two numbers in the series are 0 and 1. The following step is to make an array of size n+1 and start with 0 and 1 for the first two integers in the series.

The next step is to compute each next integer in the series using a loop. Starting at index 2, we add the first two numbers in the series, which are stored in the (i-1)th and (i-2)th indices of the array, to get the i-th number. The ith integer is subsequently placed at the array's ith index.

The nth integer in the series, which is kept in the nth index of the array, is then returned.

The Fibonacci sequence up to the nth number may then be generated by calling this function with a specified value for n.

This method is more effective for bigger values of n since it does not need to repeat the same computations as the recursive method. The approach to dynamic programming is another name for it.

### Difficulties while programming this solution

The following are some potential challenges you may run into while using Java to implement the bottom-up method for the Fibonacci series:

1. Array index out-of-bounds error: This might happen if the loop uses the incorrect array indices or if the first two members of the array aren't initialized with 0 and 1.

2. Integer overflow: The numbers associated with Fibonacci can grow fast for big values of n and may surpass the largest result that an int data type can store. Instead of using an int, you might use a long data type.

3. Off-by-one errors: To prevent missing or repeated numbers in the series, you must alter your loop circumstances, as Java's array indices begin at 0.

4. Memory use that could be improved: The bottom-up method stores all of the intermediate results in an array, which can be wasteful for very high values of n. You may use a rolling window of size 2 to save only the previous two values in the series and update them during each iteration of the loop, which will reduce memory use.

### The Top-Down Approach in Java

The memoization approach is another name for the top-down strategy used to generate the Fibonacci sequence in Java. It entails caching the intermediate outcomes of the recursive function calls in a cache (often an array or a hashmap) to avoid repeating calculations.

### How do we approach it?

The fundamental algorithm for the top-down strategy is as follows:

1. Create a cache (array or hashmap) to save the previously calculated Fibonacci numbers.

2. Create a recursive function that receives the nth Fibonacci number as an input and returns the nth integer.

3. Verify if the nth Fibonacci number has already been generated and cached in the recursive function. Return the cached value if it has. If not, recursively execute the function with the inputs n-1 and n-2 to calculate the nth Fibonacci number, then cache the result before returning it.

4. Call the recursive function using the value n as an argument to create the nth Fibonacci number.

## Fibonacci Series in Java without using recursion

Without recursion, we can construct the Fibonacci sequence in Java using a loop and an array to hold the intermediate results. Here is an illustration of the bottom-up strategy in action:

`public static int[] fibonacciSeries(int n) {Â  Â  int[] fib = new int[n+1];Â  Â  fib[0] = 0;Â  Â  fib[1] = 1;Â  Â  for (int i = 2; i <= n; i++) {Â  Â  Â  Â  fib[i] = fib[i-1] + fib[i-2];Â  Â  }Â  Â  return fib;}`

This function gives an array of size 'n+1' holding the Fibonacci sequence up to the nth term. It accepts an integer input of 'n.' The series' starting values are set to 0 and 1, and the subsequent values are generated by adding the initial two values of the series in a loop.

For high values of n, it is more effective to compute the Fibonacci sequence using a loop rather than recursion since it avoids the cost of function calls and the repetitive computation of the same numbers.

## Time And Space Complexity

Java's recursive Fibonacci series implementation has an O(2n) time complexity, where n is the input value. This is due to the function's exponentially high number of function calls, which occurs when it recursively calls itself twice for each input value until it hits the base cases.

The recursive implementation's O(n), where n is the input value, space complexity. This is so that all intermediate outcomes may be stored in the function call stack until the basic cases are reached. The call stack's maximum depth is proportionate to the given input value, resulting in linear space complexity.

Overall, the exponential time cost and the linear space complexity of the recursive approach make it exceedingly expensive for large values of n. An iterative technique, such as the bottom-up strategy, which has linear time and spatial complexity, is more effective.

## Fibonacci Number Using Memoization in Java

Memory optimization is a method for recursive algorithms that prevents unnecessary calculations by storing intermediate results.

The Fibonacci sequence is implemented in Java using the following example:

`public static int fibonacciMemoization(int n, int[] memo) {Â  Â  if (n <= 1) {Â  Â  Â  Â  return n;Â  Â  }Â  Â  if (memo[n] != 0) {Â  Â  Â  Â  return memo[n];Â  Â  }Â  Â  memo[n] = fibonacciMemoization(n-1, memo) + fibonacciMemoization(n-2, memo);Â  Â  return memo[n];}`

This approach uses an array of size 'memo' of integer 'n+1' to record the intermediate results and an integer input 'n.' The function provides the cached result if the answer to the input 'n' is already present in the memo array. If not, the procedure repeatedly invokes itself using the inputs "n-1" and "n-2.â€ť Before returning the result, it saves it in the memo array.

## Conclusion

The Fibonacci series has many applications, and Java offers several ways to generate it. The recursive approach is simple but inefficient for large values of n, while dynamic programming techniques like memoization and tabulation help reduce the time complexity to O(n) and improve space complexity.

The best approach depends on the problem's requirements and the trade-off between time and space complexity. Memoization uses a top-down approach, while tabulation uses a bottom-up approach. Another approach is the iterative method, which generates the series using a loop. It's simple and efficient but lacks the elegance of dynamic programming.

## FAQs

1. What does Java's Fibonacci sequence mean?

Beginning with 0 and 1, the Fibonacci series is a set of numbers in Java where each succeeding number is the sum of the two before it. The sequence is much like programming the palindrome series in Java- the concept remains the same, but the code changes with the necessity of desired output and interface.

2. What different methods are there for creating the Fibonacci series in Java?

Recursion, repetitive loops, and dynamic programming methods like memoization and tabulation are ways you may use Java to build the Fibonacci sequence. Much like generating the factorial series in Java, you can generate the Fibonacci sequence using multiple methods. The problem's precise needs and the trade-off between time and space complexity determine the method. You can also choose to generate the nth Fibonacci number in Java with the discussed methods.

3. How do time and space complexity vary in Java methods for producing the Fibonacci series?

For each strategy, the complexity in time and space varies. Memorization and tabulation have an O(n) time complexity, but the recursive technique has an O(2n) time complexity. Memorization and tabulation have a space difficulty of O(n) and O(1), respectively, whereas the recursive technique has a space complexity of O(n). The time and space complexity of the iterative loop method are O(n) and O(1), respectively.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

###### Need More Help? Talk to an Expert
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...