nth fibonacci number
Sure! Here is a response that provides the steps to find the nth Fibonacci number using C++:
#include<iostream>
using namespace std;
// Function to find the nth Fibonacci number
int fibonacci(int n) {
if(n <= 1) {
return n;
}
else {
int a = 0, b = 1, c;
for(int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
// Main function
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
cout << "The " << n << "th Fibonacci number is: " << fibonacci(n) << endl;
return 0;
}
Explanation of the steps:
1. The code begins by including the necessary header file iostream
, which allows input and output operations.
2. The fibonacci
function is defined, which takes an integer n
as input and returns the nth Fibonacci number.
3. In the fibonacci
function, an if
condition is used to handle the base cases where n
is 0 or 1. In these cases, the function simply returns n
.
4. If n
is greater than 1, the function enters an else
block. Here, three variables a
, b
, and c
are declared. a
and b
are initialized as the first two Fibonacci numbers, i.e., 0 and 1, respectively.
5. A for
loop is used to iterate from 2 to n
. In each iteration, c
is calculated as the sum of a
and b
, and then a
and b
are updated accordingly.
6. After the loop ends, the function returns the value of b
, which represents the nth Fibonacci number.
7. In the main
function, an integer variable n
is declared to store the user's input.
8. The user is prompted to enter the value of n
using the cout
and cin
statements.
9. The fibonacci
function is called with n
as the argument, and the returned value is displayed using the cout
statement.
10. Finally, the program ends by returning 0 from the main
function.