find nth fibonacci number
To find the nth Fibonacci number in C++, you can use either an iterative or recursive approach.
Recursive Approach:
One way to find the nth Fibonacci number is by using recursion. Here's how you can do it:
- Create a function
fibonacci
that takes an integern
as a parameter. - Inside the function, check if
n
is either 0 or 1. If it is, returnn
as the Fibonacci number. - If
n
is greater than 1, recursively call thefibonacci
function withn-1
andn-2
as parameters and add the results together. - Return the sum as the Fibonacci number.
Here's the code for the recursive approach:
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
To find the nth Fibonacci number, you can call the fibonacci
function with the desired value of n
.
Iterative Approach:
Another way to find the nth Fibonacci number is by using an iterative approach. Here's how you can do it:
- Create a function
fibonacci
that takes an integern
as a parameter. - Create two variables
a
andb
and initialize them to 0 and 1 respectively. These variables will keep track of the last two Fibonacci numbers. - Use a loop to iterate
n-1
times. - In each iteration, update
a
andb
by swapping their values and addinga
andb
together. - After the loop,
b
will hold the nth Fibonacci number. - Return the value of
b
as the Fibonacci number.
Here's the code for the iterative approach:
int fibonacci(int n) {
if (n <= 1)
return n;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int temp = a + b;
a = b;
b = temp;
}
return b;
}
To find the nth Fibonacci number, you can call the fibonacci
function with the desired value of n
.
Both the recursive and iterative approaches will give you the same result. The recursive approach is more straightforward and easier to understand, but it can be less efficient for large values of n
due to the repeated calculations. The iterative approach is more efficient as it avoids repeated calculations by using a loop to calculate the Fibonacci numbers iteratively.