Answer to Question #252237 in Java | JSP | JSF for Rob

Question #252237

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:

  • fibRecursive() - receive value of i from main() and perform fibonacci
  • fibIteration() - receive value of i from main () and perform fibonacci
  • main() - accept a value (i) to be used as the output of fibonacci


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.



1
Expert's answer
2021-10-17T01:45:44-0400
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.");
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS