nth Fibonacci Number

Program to find the nth Fibonacci number

BeginnerTopic: Loop Programs
Back

C++ nth Fibonacci Number Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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

Understanding nth Fibonacci Number

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.

---

1. 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
3 + 5 = 8
And so on...

Applications:

Nature: Flower petals, pinecones, shells follow Fibonacci patterns
Computer science: Dynamic programming, algorithm design
Mathematics: Golden ratio, number theory
Art and design: Aesthetic proportions

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring Variables

int n, first = 0, second = 1, next;

Variable `n`:

Stores the position in Fibonacci sequence
User wants to find the nth Fibonacci number

Variable `first`:

Stores the first of the two previous numbers

-

Initialized to 0

(F(0) = 0)

Variable `second`:

Stores the second of the two previous numbers

-

Initialized to 1

(F(1) = 1)

Variable `next`:

Temporarily stores the next Fibonacci number
Calculated as: next = first + second

Why these initial values?

Fibonacci sequence starts: 0, 1, ...
first = 0 represents F(0)
second = 1 represents F(1)

---

4. Taking Input From User

`cout << "Enter the position (n): ";`

cin >> n;

Prompts user to enter position
Reads and stores it in n

Example:

User enters:

10

n = 10 (wants 10th Fibonacci number)

---

5. Handling Base Cases

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;`

Why handle these separately?

Position 1: F(1) = 0 (stored in first)
Position 2: F(2) = 1 (stored in second)
These are already known, no calculation needed

What happens:

If n == 1: Print first (0) and exit
If n == 2: Print second (1) and exit
Otherwise: Continue to calculation

---

6. Calculating Fibonacci Numbers Iteratively

for (int i = 3; i <= n; i++)

next = first + second;

first = second;

second = next;

How it works:

We start from position 3 because positions 1 and 2 are already handled.

Step-by-step (for n = 10):

Initial:

first = 0, second = 1

Iteration 1 (i = 3):

Calculate: next = 0 + 1 = 1 (F(3))
Update: first = 1, second = 1
Now: first = F(2), second = F(3)

Iteration 2 (i = 4):

Calculate: next = 1 + 1 = 2 (F(4))
Update: first = 1, second = 2
Now: first = F(3), second = F(4)

Iteration 3 (i = 5):

Calculate: next = 1 + 2 = 3 (F(5))
Update: first = 2, second = 3
Now: first = F(4), second = F(5)

... continue ...

Iteration 8 (i = 10):

Calculate: next = 13 + 21 = 34 (F(10))
Update: first = 21, second = 34
Now: first = F(9), second = F(10)

After loop:

second = 34 ✅ (F(10) = 34)

---

7. Understanding Variable Swapping

The key pattern:

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

Visual representation:

Iteration 1:

first = 0, second = 1

next = 0 + 1 = 1

first = 1, second = 1 (moved forward)

Iteration 2:

first = 1, second = 1

next = 1 + 1 = 2

first = 1, second = 2 (moved forward)

Iteration 3:

first = 1, second = 2

next = 1 + 2 = 3

first = 2, second = 3 (moved forward)

---

8. Complete Example Walkthrough

Input:

n = 10 (want 10th Fibonacci number)

Step 1: Check base cases

n == 1

false

n == 2

false

Continue to calculation

Step 2: Initialize

first = 0 (F(1))
second = 1 (F(2))

Step 3: Calculate iteratively

Loop from i = 3 to 10
Each iteration calculates next number and updates first/second

Step 4: Result

After 8 iterations, second = 34
F(10) = 34 ✅

Verification:

Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,

34

Position 10 = 34 ✅

---

9. Displaying the Result

`cout << "Fibonacci number at position " << n << " is: " << second << endl;`

This prints:

Text: "Fibonacci number at position "
Position: 10
Text: " is: "
Value: 34
New line

Output:

Fibonacci number at position 10 is: 34

---

10. Why This Approach is Efficient

Iterative approach (our method):

Time complexity: O(n)
Space complexity: O(1) - only uses a few variables
Very efficient for large n

Recursive approach (alternative):

int fib(int n) {

if (n <= 1) return n;

}

Time complexity: O(2^n) - exponential!
Very slow for large n
Our iterative approach is much better

---

    return fib(n-1) + fib(n-2);

11. Fibonacci Sequence Table

First 15 Fibonacci numbers:

| Position | Value |

|----------|-------|

| 1 | 0 |

| 2 | 1 |

| 3 | 1 |

| 4 | 2 |

| 5 | 3 |

| 6 | 5 |

| 7 | 8 |

| 8 | 13 |

| 9 | 21 |

| 10 | 34 |

| 11 | 55 |

| 12 | 89 |

| 13 | 144 |

| 14 | 233 |

| 15 | 377 |

---

12. Edge Cases

Case 1: n = 1

Returns first = 0 ✅
F(1) = 0

Case 2: n = 2

Returns second = 1 ✅
F(2) = 1

Case 3: n = 3

Loop executes once (i = 3)
next = 0 + 1 = 1
Returns 1 ✅
F(3) = 1

Case 4: Large n

Program handles efficiently
Example: n = 50 calculates quickly

---

13. Real-World Applications

Nature:

Petal counts in flowers
Spiral patterns in shells
Branching in trees

Computer Science:

Dynamic programming problems
Algorithm design patterns
Optimization problems

Mathematics:

Golden ratio: F(n+1)/F(n) approaches φ ≈ 1.618
Number theory research

---

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

Understanding Fibonacci helps in:

Dynamic programming
Algorithm optimization
Mathematical problem solving
Many competitive programming problems

The Fibonacci sequence is one of the most beautiful and important sequences in mathematics, and this program demonstrates an efficient way to calculate it iteratively.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for nth Fibonacci Number

This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents