fibonacci sequence

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 8 Exercise 3
Using std_lib_facilities.h by Bjarne Stroustrup.

main.cpp main file

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PP
// Chapter 8 Exercise 3

#include "std_lib_facilities.h"

void print(string& _label, vector<int>& _vecInput) {
for (int x : _vecInput) {
cout << _label << " " << x << "\n";
}
}

void fibonacci(int x, int y, vector<int>& v, int n) {
v.push_back(x);
v.push_back(y);
for (int i = 0; i < n; i++) {
int temp;
v.push_back(x + y);
temp = y;
y = x + y;
x = temp;
}
}

int main()
try
{
vector<int> myVec;
string label = "l";
int num = 20;

fibonacci(1, 2, myVec, num);

print(label, myVec);

keep_window_open();

}

catch (runtime_error e) {
cout << e.what() << "\n";
keep_window_open();
}

catch(…) {
cout << "Exiting\n";
keep_window_open();
}
[/code]

Output:
l 1
l 2
l 3
l 5
l 8
l 13
l 21
l 34
l 55
l 89
l 144
l 233
l 377
l 610
l 987
l 1597
l 2584
l 4181
l 6765
l 10946
l 17711
l 28657
Please enter a character to exit

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply

Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124