Write a java program to print Fibonacci series up to N number, where N is the input integer. In this tutorial, We are going to write a java code to print fibonacci series.
What is Fibonacci Series?
In Fibonacci series, the first two numbers are 0 and 1 and each subsequent number is the sum of previous two numbers.
For example – 0 ,1 , 1, 2, 3, 5, 8, 13, 21 ……………….
In mathematical terms, the Nth term of Fibonacci numbers is defined by the recurrence relation.
Fibonacci(N) = Fibonacci(N – 1) + Fibonacci(N – 2)
whereas Fibonacci(0) = 0 and Fibonacci(1) = 1
C program to print Fibonacci series using recursion
Java Program to Print Fibonacci Series up to N using For loop
We have discussed, What is Fibonacci series? Let’s write a java program to print Fibonacci series up to N number using for loop. I am using an iterative approach to print Fibonacci series.
Difference between recursion and iteration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package fibonacciseries; import java.util.*; public class FibonacciSeries { /** * @param args the command line arguments */ public static void main(String[] args) { int first = 0; int second = 1; Scanner in = new Scanner(System.in); System.out.println("How many elements you want to print in a Fibonacci series"); int n = in.nextInt(); System.out.println("Fibonacci series"); System.out.print(first + " "+ second + " "); int next; /*First two elements of a Fibonacci series is 0 and 1, so we started a loop from index 2 */ for(int i = 2; i < n; i++) { //next number is the sum of previous two numbers next = first + second; System.out.print(next + " "); //previous two numbers assignment first = second; second = next; } } } |
Print Fibonacci Series in Java using While Loop
We have written a code to print Fibonacci series in java using For loop. Let’s do a little modification and print Fibonacci series in java using while loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package fibonacciseries; import java.util.*; public class FibonacciSeries { /** * @param args the command line arguments */ public static void main(String[] args) { int first = 0; int second = 1; Scanner in = new Scanner(System.in); System.out.println("How many elements you want to print in a Fibonacci series"); int n = in.nextInt(); System.out.println("Fibonacci series"); System.out.print(first + " "+ second + " "); int next; //Start a loop from second index int i = 2; //while i is less than the value of n while(i < n) { next = first + second; System.out.print(next + " "); first = second; second = next; //increment the value of i i++; } } } |