Write a Java program that uses both recursive and non-recursive (iterative)
functions to print the nth value in the Fibonacci sequence by using these methods:
The output should be:
Enter value of i: 12
Fibonacci number 12 is 144. --> This is displayed through Iterative Method.
Fibonacci number 12 is 144 --> This is displayed through Recursive Method.
import java.util.Scanner;
public class Main {
public static int fibRecursion(int i) {
if (i == 1 || i == 2) {
return 1;
}
return fibRecursion(i - 2) + fibRecursion(i - 1);
}
public static int fibIteration(int i) {
int one = 1;
int two = 1;
if (i == 1 || i == 2) {
return 1;
}
for (int n = 3; n <= i; n++) {
two = one + two;
one = two - one;
}
return two;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter value of i: ");
int i = in.nextInt();
System.out.println("Fibonacci number " + i + " is " + fibIteration(i) + ". --> This is displayed through Iterative Method.");
System.out.println("Fibonacci number " + i + " is " + fibRecursion(i) + ". --> This is displayed through Recursive Method.");
}
}
Comments
Leave a comment