nth Fibonacci Number

Program to find the nth Fibonacci number

C++Beginner
C++
#include <iostream>
using namespace std;

int main() {
    int n, first = 0, second = 1, next;
    
    cout << "Enter the position (n): ";
    cin >> n;
    
    if (n == 1) {
        cout << "Fibonacci number at position " << n << " is: " << first << endl;
    } else if (n == 2) {
        cout << "Fibonacci number at position " << n << " is: " << second << endl;
    } else {
        for (int i = 3; i <= n; i++) {
            next = first + second;
            first = second;
            second = next;
        }
        cout << "Fibonacci number at position " << n << " is: " << second << endl;
    }
    
    return 0;
}

Output

Enter the position (n): 10
Fibonacci number at position 10 is: 34

nth Fibonacci Number in C++

This program finds the nth number in the Fibonacci sequence. The Fibonacci sequence is one of the most famous sequences in mathematics, appearing in nature, art, and computer science. Each number is the sum of the two preceding numbers. This program demonstrates iterative calculation, variable swapping, and sequence generation.

What is the Fibonacci Sequence?

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones.

Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

Mathematical definition:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

How it works:

  • Start with 0 and 1
  • Next number = previous + previous previous
  • 0 + 1 = 1
  • 1 + 1 = 2
  • 1 + 2 = 3
  • 2 + 3 = 5
  • And so on...

Understanding Variable Swapping

The key pattern:

cpp
next = first + second;    // Calculate next number
first = second;            // Move second to first
second = next;             // Move next to second

Why this works:

  • We only need the last two numbers to calculate the next
  • After each iteration:
    • first = previous second (F(n-1))
    • second = newly calculated next (F(n))
  • This "slides" the window forward

Summary

  • Fibonacci sequence: each number = sum of previous two
  • Start with F(1) = 0, F(2) = 1
  • Iterative approach: calculate from position 3 onwards
  • Use variable swapping to track last two numbers
  • Time complexity: O(n), Space: O(1) - very efficient
  • Handle base cases (n = 1, n = 2) separately

This program teaches:

  • Iterative sequence generation
  • Variable swapping technique
  • Efficient algorithm design
  • Handling base cases
  • Mathematical sequence patterns