# Java program to print Fibonacci sequence

Write a Java program that uses both recursive and non-recursive functions to print nth value in the Fibonacci sequence

Without recursion:

```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import java.util.Scanner; class fibonacci { public static void main(String[] input) { int x,y; x=Integer.parseInt(input[0]); y=Integer.parseInt(input[1]); Scanner s=new Scanner(System.in); System.out.println(“Enter the value of n:”); int n=s.nextInt(); int z[]=new int[n]; z[0]=x; z[1]=y; for(int i=2;i<n;i++) { z[i]=z[i-1]+z[i-2]; } for(int i=0;i<n;i++) { System.out.println(z[i]); } } }```

With recursion:

```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.util.Scanner; class fibonacci { public static void main(String[] args) { Scanner s=new Scanner(System.in); System.out.println(“Enter the value of n:”); int n=s.nextInt(); fiboni f1=new fiboni(); System.out.println(f1.fibon(n)); } } class fiboni { public int fibon(int a) { if(a==0 || a==1) return 1; else return fibon(a-1)+fibon(a-2); } }```

Output:

Start exploring endless computing possibilities with your own Raspberry Pi computer and accessories. Perfect for beginners and students.

10

1
1
2
3
5
8
13
21
34
55

### 7 Responses to “Java program to print Fibonacci sequence”

1. wow…. i dnt knw wat to say….!!! but u didnt hav any comment abut ur program dat’s y i am publishin a comment…
….i really cant understand ur programs coz u hav sum kind of thing wich is not in my syllabus…..

anyway i appreciate u 4 takin effort to publish …

Reply
2. Your code snippet is not right it’s printing your output only no matter what I take as input. but thanks neway for your code snippet.

Reply
3. sorry I had some mistakes in my code that’s why your program didn’t execute properly.

Reply
4. Edwin Waithanji Maina

Please prepare for me a MS word document to explain the entire project

Reply
5. Edwin Waithanji

Hey. Am still waiting for a Ms word that will explain to me the entire program.I’ll appreciate

Reply

### Research Papers

Click Here to Submit

### Projects

Click Here to Submit

##### Free email signup

Get latest projects, articles in your mail box, subscribe to electrifriends

Email: