SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:5 | ISBN:9780132830317 | Edition: 5

Question

Write a recursive method definition for a static method that has one parameter n of type int and that returns the n th Fibonacci number. The Fibonacci numbers are is 1, is 1, is 2, is 3, is 5, and in general

= + for i = 0, 1, 2, ...

Place the method in a class that has a main that tests the method.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.*;

public class FibonacciTest 
{
	public static void main(String args[])
	{

		Scanner input = new Scanner(System.in);
		System.out.print("Enter number:");
		int n = input.nextInt();
		
		System.out.println("Febonnacci number result: " + fibonacci(n));
	}
	public static int fibonacci(int f) 
	{
		if (f == 0)
			return 1;
		else if (f == 1)
			return 1;
		else
			return fibonacci(f - 1) + fibonacci(f - 2);
	}

	
}


Result:

Enter number:15
Febonnacci number result: 987

 

0 0

Discussions

Post the discussion to improve the above solution.