nth Fibonacci Number
Program to find the nth Fibonacci number
C++ nth Fibonacci Number Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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;
}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:
How it works:
Applications:
---
2. Header File: #include <iostream>
#include <iostream>
Provides:
cout → for displaying outputcin → for reading input---
3. Declaring Variables
int n, first = 0, second = 1, next;
Variable `n`:
Variable `first`:
-
Initialized to 0
(F(0) = 0)
Variable `second`:
-
Initialized to 1
(F(1) = 1)
Variable `next`:
next = first + secondWhy these initial values?
first = 0 represents F(0)second = 1 represents F(1)---
4. Taking Input From User
cin >> n;
nExample:
10
n = 10 (wants 10th Fibonacci number)---
5. Handling Base Cases
if (n == 1)
else if (n == 2)
Why handle these separately?
first)second)What happens:
n == 1: Print first (0) and exitn == 2: Print second (1) and exit---
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):
next = 0 + 1 = 1 (F(3))first = 1, second = 1Iteration 2 (i = 4):
next = 1 + 1 = 2 (F(4))first = 1, second = 2Iteration 3 (i = 5):
next = 1 + 2 = 3 (F(5))first = 2, second = 3... continue ...
Iteration 8 (i = 10):
next = 13 + 21 = 34 (F(10))first = 21, second = 34After 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:
first = previous second (F(n-1))second = newly calculated next (F(n))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
Step 2: Initialize
first = 0 (F(1))second = 1 (F(2))Step 3: Calculate iteratively
Step 4: Result
second = 34Verification:
34
---
9. Displaying the Result
This prints:
Output:
Fibonacci number at position 10 is: 34
---
10. Why This Approach is Efficient
Iterative approach (our method):
Recursive approach (alternative):
int fib(int n) {
if (n <= 1) return n;
}
---
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
first = 0 ✅Case 2: n = 2
second = 1 ✅Case 3: n = 3
next = 0 + 1 = 1Case 4: Large n
---
13. Real-World Applications
Nature:
Computer Science:
Mathematics:
---
Summary
This program teaches:
Understanding Fibonacci helps in:
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.