ต่อไปนี้คือตัวอย่างการหาอนุกรมฟีโบนักชีโดยใช้การวนซ้ำ
ตัวอย่าง
#include <iostream>
using namespace std;
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}
int main() {
int num;
cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num);
return 0;
} ผลลัพธ์
Enter the number : 10 The fibonacci series : 0 1 1 2 3 5 8 13 21 34
ในโปรแกรมข้างต้น มีโค้ดจริงอยู่ในฟังก์ชัน fib() เพื่อคำนวณอนุกรมฟีโบนักชี
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
} ในฟังก์ชัน main() ผู้ใช้จะป้อนตัวเลข ฟังก์ชัน fib() ถูกเรียกและอนุกรมฟีโบนักชีถูกพิมพ์ดังนี้ −
cout << "Enter the number : "; cin >> num; cout << "\nThe fibonacci series : " ; fib(num);