nth Fibonacci Number in C++
nth Fibonacci in C++. This program: position 1 is 0, position 10 is 34.
1#include <iostream>2using namespace std;34int main() {5 int n, first = 0, second = 1, next;67 cout << "Enter the position (n): ";8 cin >> n;910 if (n == 1) {11 cout << "Fibonacci number at position " << n << " is: " << first << endl;12 } else if (n == 2) {13 cout << "Fibonacci number at position " << n << " is: " << second << endl;14 } else {15 for (int i = 3; i <= n; i++) {16 next = first + second;17 first = second;18 second = next;19 }20 cout << "Fibonacci number at position " << n << " is: " << second << endl;21 }2223 return 0;24}
Output
Enter the position (n): 10 Fibonacci number at position 10 is: 34
What's going on
Fibonacci here: each term is the sum of the two before it. This program treats position 1 as 0, position 2 as 1, position 10 as 34.
That's 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Some books call 34 F(9) because they start at F(0)=0. This file starts counting at 1. Read the if (n == 1) branch before arguing with the sample.
int n, first = 0, second = 1, next;
n == 1 → print 0.
n == 2 → print 1.
Else from i = 3 to n:
next = first + second;
first = second;
second = next;
Walk to 10:
Print second. Sample: Fibonacci number at position 10 is: 34.
Naive recursion fib(n-1)+fib(n-2) is the same sequence with exponential time. This loop is O(n) and a handful of ints.
int overflows around position 47. long long if you go further.