หาลำดับฟีโบนัชชีด้วย Iteration
ตัวอย่างหาลำดับฟีโบนัชชีโดยใช้การวนรอบ (iteration)
ตัวอย่างโค้ด
#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() คำนวณฟีโบนัชชีด้วยตัวแปร x, y, z วนลูป num รอบ main() รับค่าจากผู้ใช้ เรียก fib() แสดงผล