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:

  1. Create a function fibonacci that takes an integer n as a parameter.
  2. Inside the function, check if n is either 0 or 1. If it is, return n as the Fibonacci number.
  3. If n is greater than 1, recursively call the fibonacci function with n-1 and n-2 as parameters and add the results together.
  4. 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:

  1. Create a function fibonacci that takes an integer n as a parameter.
  2. Create two variables a and b and initialize them to 0 and 1 respectively. These variables will keep track of the last two Fibonacci numbers.
  3. Use a loop to iterate n-1 times.
  4. In each iteration, update a and b by swapping their values and adding a and b together.
  5. After the loop, b will hold the nth Fibonacci number.
  6. 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.