Fibonacci Sequence

suggest change

You can calculate a number in the Fibonacci sequence using recursion.

For n greater than 2, F(n) = F(n-2) + F(n-1). F(1) and F(2) are both 1.

// Returns the i'th Fibonacci number
public int fib(int i) {
    if (i <= 0)
        throw new ArgumentOutOfRangeException(nameof(i));
    if (i <= 2) {
        // F(1) and F(2) are both 1.
        return 1;
    }
    // Recursive case. Return the sum of the two previous Fibonacci numbers.
    // This works because the definition of the Fibonacci sequence specifies
    // that the sum of two adjacent elements equals the next element.
    return  fib(i - 2) + fib(i - 1);
    
}

fib(10); // Returns 55

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents