# fibonacci

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. In C++, you can write a program to calculate the Fibonacci sequence using recursion or iteration.

Here is an example of a C++ program to calculate the Fibonacci sequence using recursion:

```
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
return 0;
}
```

Explanation of the code:

The program starts with including the necessary header file

`iostream`

, which is used for input and output operations in C++.The

`fibonacci()`

function is defined to calculate the Fibonacci sequence. It takes an integer`n`

as a parameter and returns the`n`

th term of the sequence.In the

`fibonacci()`

function, there is a base case where if`n`

is less than or equal to 1, it returns`n`

. This base case is necessary to stop the recursion.If the base case is not met, the function recursively calls itself with

`n - 1`

and`n - 2`

as parameters and returns the sum of the two recursive calls.In the

`main()`

function, an integer`n`

is declared to store the number of terms the user wants to calculate.The user is prompted to enter the number of terms.

A

`for`

loop is used to iterate from 0 to`n - 1`

.Inside the loop, the

`fibonacci()`

function is called with the current index (`i`

) as the argument, and the result is printed.Finally, the program returns 0 to indicate successful execution.

This program calculates the Fibonacci sequence by recursively calling the `fibonacci()`

function. The base case ensures that the recursion stops when `n`

is less than or equal to 1. The `main()`

function prompts the user for input and prints the calculated Fibonacci sequence using a `for`

loop.