My issue
using namespace std;
int fib(int n) {
if (n <= 1) {
return n;
}
int a = 0; // Initialize first Fibonacci number (fib(0))
int b = 1; // Initialize second Fibonacci number (fib(1))
int fib_num = 0; // Variable to store nth Fibonacci number
// Calculate nth Fibonacci number iteratively
for (int i = 2; i <= n; ++i) {
fib_num = a + b;
a = b;
b = fib_num;
}
return fib_num;
}
int main() {
int n;
cin >> n;
cout << fib(n) << endl;
return 0;
}
it shows hidden error give it correct.
My code
#include <iostream>
using namespace std;
int fib(int n) {
if (n <= 1) {
return n;
}
int a = 0; // Initialize first Fibonacci number (fib(0))
int b = 1; // Initialize second Fibonacci number (fib(1))
int fib_num = 0; // Variable to store nth Fibonacci number
// Calculate nth Fibonacci number iteratively
for (int i = 2; i <= n; ++i) {
fib_num = a + b;
a = b;
b = fib_num;
}
return fib_num;
}
int main() {
int n;
cin >> n;
cout << fib(n) << endl;
return 0;
}
Learning course: Design and Analysis of Algorithms
Problem Link: Fibonacci Series in Design and Analysis of Algorithms