VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-for-fibonacci-numbers/

⇱ C++ Program For Fibonacci Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program For Fibonacci Numbers

Last Updated : 27 May, 2026

The Fibonacci series is a sequence in which each number is the sum of the previous two numbers. The series starts with 0 and 1, and the remaining terms are generated using the relation:

F(n)=F(nāˆ’1)+F(nāˆ’2)

where:

  • F(0) = 0
  • F(1) = 1

Example:

Input: 5
Output: 5

Explanation: In the Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13..., the value at index 5 is 5 (using 0-based indexing).

Different Ways to Find Nth Fibonacci Number in C++

There are multiple approaches to find the nth Fibonacci number in C++. Each method has different time and space complexities.

Using Recursion

The simplest way to find the nth Fibonacci number is by using recursion. In this method, the function repeatedly calls itself to calculate previous Fibonacci numbers.

Approach:

  • If n is 0 or 1, return n.
  • Otherwise, recursively calculate: F(n)=F(nāˆ’1)+F(nāˆ’2)

Output
5

Explanation: The function recursively calculates the Fibonacci value by adding the previous two Fibonacci numbers.

  • Time Complexity: O(2n)
  • Auxiliary Space: O(n)

Optimization of Recursion Method

The recursive solution can be optimized by passing the previous two Fibonacci numbers as parameters. This avoids repeated calculations.

Approach:

  • Store the previous two Fibonacci numbers.
  • Update them during recursive calls.
  • Avoid recalculating already computed values.

Output
5

Explanation: Instead of recalculating previous Fibonacci numbers, the function carries forward the last two values in each recursive call.

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Using Loops

The iterative approach using loops is one of the most efficient and commonly used methods.

Approach:

  • Maintain two variables for previous Fibonacci numbers.
  • Use a loop to generate the next Fibonacci term.
  • Continue until the nth term is reached.

Output
5

Explanation: The loop continuously updates the last two Fibonacci numbers until the required term is found.

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)

Using Matrix Exponentiation

In this approach, the Fibonacci series is represented using a transformation matrix based on the Fibonacci relation:

F(n)=F(nāˆ’1)+F(nāˆ’2)

where:

  • F(0) = 0
  • F(1) = 1

This method efficiently calculates the nth Fibonacci number by raising the transformation matrix to the power (n - 1). Matrix exponentiation uses the divide-and-conquer technique to compute powers quickly, making it much faster for large values of n.


Output
5

Explanation: Matrix exponentiation reduces repeated calculations by using divide-and-conquer techniques.

  • Time Complexity: O(log n)
  • Auxiliary Space: O(log n)
Comment