Java program to print Fibonacci sequence Recursive & Non Recursive

The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it. Write a Java program that uses both recursive and non-recursive functions to print
the nth value of the Fibonacci sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*Non Recursive Solution*/
import java.util.Scanner;
class Fib {
	public static void main(String args[ ]) {
		Scanner input=new Scanner(System.in);
		int i,a=1,b=1,c=0,t;
		System.out.println("Enter value of t:");
		t=input.nextInt();
		System.out.print(a);
		System.out.print(" "+b);
		for(i=0;i<t-2;i++) {
			c=a+b;
			a=b;
			b=c;
			System.out.print(" "+c);
		}
		System.out.println();
		System.out.print(t+"th value of the series is: "+c);
	}
}
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
/* Recursive Solution*/
import java.io.*;
import java.lang.*;
class Demo {
	int fib(int n) {
		if(n==1)
			return (1);
		else if(n==2)
			return (1);
		else
			return (fib(n-1)+fib(n-2));
	}
}
class RecFibDemo {
	public static void main(String args[])throws IOException {
		InputStreamReader obj=new InputStreamReader(System.in);
		BufferedReader br=new BufferedReader(obj);
		System.out.println("enter last number");
		int n=Integer.parseInt(br.readLine());
		Demo ob=new Demo();
		System.out.println("fibonacci series is as follows");
		int res=0;
		for(int i=1;i<=n;i++) {
			res=ob.fib(i);
			System.out.println(" "+res);
		}
		System.out.println();
		System.out.println(n+"th value of the series is "+res);
	}
}
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

11 thoughts on “Java program to print Fibonacci sequence Recursive & Non Recursive

  1. Hey guys. Its Edwin, a new learner in java,please send me a Ms word document to explain the whole program that uses both recursive and non recursive functions to print the nth value of a Fibonacci sequence. I will appreciate

  2. for(int i=1;i<=n;i++) {
    res=ob.fib(i);
    System.out.println(" "+res);
    }

    this is not recursive, we need one function to be called and it shoud be recursive.

  3. HI ranjit,this is vijay krishna.actually in ur fibonocci series recursive program give exception because it takes 0 what it will return.so for my suggestion u can make as n==2 to n==0 in fib function

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in