Introduction
In this lab, you will learn how to write a C++ program to find the Fibonacci series using functions. We will show you two different solutions to the problem. You can choose the one that suits your needs.
In this lab, you will learn how to write a C++ program to find the Fibonacci series using functions. We will show you two different solutions to the problem. You can choose the one that suits your needs.
We will now write the code to find the Fibonacci series. We will write two different programs, one to find the Fibonacci series up to n terms and the other to find the Fibonacci series up to a specific number.
This program generates the Fibonacci series up to n number of terms.
#include <iostream>
using namespace std;
void fibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm = 0;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
fibonacci(n);
return 0;
}
This program generates the Fibonacci sequence up to a certain number.
#include <iostream>
using namespace std;
void fibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm = 0;
// displays the first two terms which is always 0 and 1
cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";
nextTerm = t1 + t2;
while(nextTerm <= n) {
cout << nextTerm << ", ";
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
}
int main() {
int n;
cout << "Enter a positive number: ";
cin >> n;
fibonacci(n);
return 0;
}
To compile and run the above programs, you need to follow the below mentioned steps:
~/project
directoryg++ main.cpp -o main
./main
In this lab, we learned how to write a C++ program to find the Fibonacci series using functions. We wrote two programs, one to find the Fibonacci series up to n terms and the other to find the Fibonacci series up to a specific number.