Fibonacci Series Using Iterative Approach
Initialize the first and second numbers to 0 and 1. Following this, we print the first and second numbers. Then we send the flow to the iterative while loop where we get the next number by adding the previous two numbers and simultaneously we swap the first number with the second and the second with the third.
Below is the implementation of the Iterative Approach to Print Fibonacci Series in Java:
// Fibonacci series program in java
import java.io.*;
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
for (int i = 0; i < N; i++) {
// Print the number
System.out.print(num1 + " ");
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}
The complexity of the above method
Time Complexity: O(N)
Auxiliary Space: O(1)
Program to Print Fibonacci Series in Java
The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. In this article, we will learn how to print Fibonacci Series in Java up to the N term, where N is the given number.
Examples of Fibonacci Series in Java
Input: N = 10
Output: 0 1 1 2 3 5 8 13 21 34
Explanation: Here first term of Fibonacci is 0 and second is 1, so that 3rd term = first(o) + second(1) etc and so on.
There are 4 ways to write the Fibonacci Series program in Java:
- Fibonacci Series Using Iterative Approach
- Fibonacci Series Using Recursive Approach
- Fibonacci Series Using Memoization
- Fibonacci Series Using Dynamic Programming