Recursion

19.5 - Recursive Fibonacci


The Fibonacci numbers, denoted Fn can be calculated recursively. It follows this rule:

  • F0 = 0
  • F1 = 1
  • Fn = Fn-1 + Fn-2

Task

Define the function int fibonacci(int n) which gives the nth Fibonacci number by using recursion.

  • Define the base cases for 0 and 1.
  • Define the recursion cases.
#include <iostream> int fibonacci(int n) { // Define this function. } int main() { int n{}; std::cin >> n; std::cout << fibonacci(n) << std::endl; }