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)) } }

JF
Answered by Jordan F. Computing tutor

2293 Views

See similar Computing A Level tutors

Related Computing A Level answers

All answers ▸

Simplify the boolean expression ¬(A.B)+A.


What is the difference between simplex, half duplex and full duplex?


What is the time complexity of Bubble Sort?


What are the different development methodologies and what are their advantages and disadvantages?


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

MyTutor is part of the IXL family of brands:

© 2025 by IXL Learning