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.
/*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);
}
}
Expected Input and output:
Enter the value of t: 5 1 1 2 3 5
Actual Input & Output :
For more info regarding technology and pro stuff...visit http://peoplezmind.com/
/*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);
}
}
Expected Input and output:
Enter the value of t: 5 1 1 2 3 5
Actual Input & Output :
For more info regarding technology and pro stuff...visit http://peoplezmind.com/
view-source:http://127.0.0.1:8889/e2b39ccf-5e87-47e8-99cf-f7a7b36d810d
ReplyDeletehttp://127.0.0.1:8889/2e1abcd9-d8b9-4c57-b172-f5afb36e065a