Drill

ProblemsC++ › warmup

Nth Fibonacci number

easywarmupMathRecursionC++

Return the nth number in the Fibonacci sequence, counting from zero.

fibonacci(n: int) → int

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int fibonacci(int n) {
    
}

Worked examples

CallResult
fibonacci(0)0
fibonacci(1)1
fibonacci(2)1
fibonacci(10)55

Hint

Keep two variables and slide them forward. No recursion needed.

Reference solution in C++
int fibonacci(int n) {
    int a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        int next = a + b;
        a = b;
        b = next;
    }
    return a;
}

The same problem in another language

More warmup problems in C++