Write a small program, in pseudocode or otherwise, that demonstrates a recursive algorithm. Write a small explanation of how recursion is used in your program.

The Fibonacci sequence is defined as:f(n) = f(n-1) + f(n-2)F(0) = 1F(1) = 1Where n is a positive number. This allows for a recursive algorithm to be written that returns 1 for the two base cases, and returns the sum of calling the function on n - 1 and n - 2 for any other case.public class RecursionDemonstration { public static int recursiveFibonacci(int n) { // Sanity check that n > 0 if (n < 0) { // return -1 to signal an error. return -1; } // check for the base case. if (n == 0 || n == 1) { return 1; } else { return (recursiveFibonacci(n-1) + recursiveFibonacci(n-2); } } public static void main(String[] args) { System.out.println("The 0th fibonacci number is " + Integer.toString(recursiveFibonacci(0)); System.out.println("The 1st fibonacci number is " + Integer.toString(recursiveFibonacci(1)); System.out.println("The 2nd fibonacci number is " + Integer.toString(recursiveFibonacci(2)); System.out.println("The 7th fibonacci number is " + Integer.toString(recursiveFibonacci(7)) } }

Answered by Jordan F. Computing tutor

1890 Views

See similar Computing A Level tutors

Related Computing A Level answers

All answers ▸

Write pseudocode for the binary search algorithm and state, with an explanation, it's worst case complexity in big-O notation


How can the idea of precondtioning as part of 'Thinking Ahead' benefit a programmer when writing code?


What are the main differences between different loops when it comes to coding ?


Explain indexed addressing including the benefits when traversing certain data structures (4 Marks)


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences