The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In mathematical terms, it is defined by the recurrence relation:
F(n) = F(n-1) + F(n-2)
C++ program to display the Fibonacci series:
#include <iostream>
namespace std;
void fibonacciUpToNTerms(int n) {
int first = 0, second = 1;
cout << "Fibonacci Series up to " << n << " terms: ";
for (int i = 0; i < n; ++i) {
cout << first << " ";
int next = first + second;
first = second;
second = next;
}
cout << endl;
}
void fibonacciUpToNumber(int maxNumber) {
int first = 0, second = 1;
cout << "Fibonacci Series up to " << maxNumber << ": ";
while (first <= maxNumber) {
cout << first << " ";
int next = first + second;
first = second;
second = next;
}
cout << endl;
}
int main() {
int n_terms = 10;
fibonacciUpToNTerms(n_terms);
int max_number = 50;
fibonacciUpToNumber(max_number);
return 0;
}
Output:
Fibonacci Series up to 10 terms: 0 1 1 2 3 5 8 13 21 34
Fibonacci Series up to 50: 0 1 1 2 3 5 8 13 21 34
Explanation:
- For the first part, the program prints the Fibonacci series up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
- For the second part, it prints the Fibonacci series up to the maximum number 50 without exceeding it.
- `fibonacciUpToNTerms` function generates and prints the Fibonacci series up to a specified number of terms.
- `fibonacciUpToNumber` function generates and prints the Fibonacci series up to a specified maximum number.
We can also modify the values of `n_terms` and `max_number` to see different results.