C/C++ Program for the n-th Fibonacci number?

The Fibonacci sequence is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

In this problem, we will find the nth number in the Fibonacci series. For this we will calculate all the numbers and print the n terms.

Syntax

// Basic approach using loop
for (i = 1; i <= n; ++i) {
    // Calculate next term based on previous two terms
}

Example Input/Output

Input: 8
Output: 0 1 1 2 3 5 8 13

Explanation

0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13

Method 1: Using For Loop

This approach uses a for loop to calculate the sum of previous two terms for the next term −

#include <stdio.h>

int main() {
    int t1 = 0, t2 = 1, n, i, nextTerm;
    n = 8;
    
    for (i = 1; i <= n; ++i) {
        if (i == 1) {
            printf("%d ", t1);
            continue;
        }
        if (i == 2) {
            printf("%d ", t2);
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        printf("%d ", nextTerm);
    }
    printf("\n");
    return 0;
}
0 1 1 2 3 5 8 13 

Method 2: Using Recursion

This approach uses recursion to calculate Fibonacci numbers −

#include <stdio.h>

int fibonacci(int n) {
    if (n <= 1)
        return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int n = 8;
    int i;
    
    for (i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }
    printf("\n");
    return 0;
}
0 1 1 2 3 5 8 13 

Key Points

  • The iterative approach has O(n) time complexity and O(1) space complexity.
  • The recursive approach has O(2^n) time complexity due to repeated calculations.
  • For better performance with recursion, consider using dynamic programming or memoization.

Conclusion

The Fibonacci sequence can be generated using either iterative or recursive approaches. The iterative method is more efficient for larger values of n due to its linear time complexity.

Updated on: 2026-03-15T11:35:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements