Java program to display fibonacci sequence up to n has been shown here. Here n is the limit up to which the sequence is to be generated. For example if n = $20$, we get the fibonacci numbers up to $20$ i.e. $0, 1, 1, 2, 3, 5, 8, 13$. The following section covers the iterative and recursive approaches to find fibonacci sequence. The algorithm, pseudocode of the program have been shown below.
Page content(s):
1. Algorithm to display fibonacci sequence upto n
1. Take the limit n as input.
2. Assign the first two fibonacci numbers to variables a, b i.e. a = 0 and b = 1
3. If n = 0, display a else, display a, b.
4. Check if a + b <= n
5. If step 4 is true perform step 6 to 8, else stop the process
6. t = a + b and display t
7. a = b and b = t
8. Go to step 4
2. Pseudocode to display fibonacci sequence upto n
Input : A limit $n$
Output : Fibonacci sequence upto $n$
1. Procedure fibonacciUptoN($n$):
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13. End Procedure
3. Java Program & output to display fibonacci sequence upto n using iteration
/******************************* alphabetacoder.com Java program to find fibonacci series up to N using iteration ********************************/ import java.util.Scanner; class Main { public static void main(String args[]) { // declare object of Scanner class Scanner sc = new Scanner(System.in); // declare variables int n, a, b, t = 0; // take input of the limit System.out.print("Enter the limit = "); n = sc.nextInt(); // intialize the first two terms of the sequence a = 0; b = 1; System.out.print("Fibonacci sequence upto " + n + ": "); // display the first fibonacci if (n == 0) System.out.print(a); // display first two fibonacci else System.out.print(a + " " + b); //now calculate the remaining terms upto n while (a + b <= n) { // calculate next fibonacci t = a + b; //display next fibonacci System.out.print(t + " "); //assign values for next iteration a = b; b = t; } } }
Output
Enter the limit = 20
Fibonacci sequence upto 50: 0 1 1 2 3 5 8 13
4. Java Program & output to display fibonacci sequence upto n using recursion
/******************************* alphabetacoder.com Java program to find fibonacci series up to N using iteration ********************************/ import java.util.Scanner; class Main { // recursive function to display // fibonacci sequence static void fibonacci(int a, int b, int n) { if (a <= n) { System.out.print(a + " "); fibonacci(b, a + b, n); } } public static void main(String args[]) { // declare object of Scanner class Scanner sc = new Scanner(System.in); // declare variables int n; // take input of the limit System.out.print("Enter the limit = "); n = sc.nextInt(); System.out.print("Fibonacci sequence upto " + n + ": "); // call the function // pass value of the first two // terms and limit fibonacci(0, 1, n); } }
Output
Enter the limit = 50
Fibonacci sequence upto 50: 0 1 1 2 3 5 8 13 21 34