English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++Program Uses Iterative Search to Find Fibonacci Numbers

The following is an example of using iteration to find the fibonacci series.

Example

#include <iostream>
using namespace std;
void fib(int num) {
   int x = 0, y = 1, z = 0;
   for (int i = 0; i < num;++) {
      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;
}

Output Result

Enter the number: 10
The fibonacci series: 0 1 1 2 3 5 8 13 21 34

In the above program, the actual code exists within the function fib() to calculate the fibonacci series.

void fib(int num) {
   int x = 0, y = 1, z = 0;
   for (int i = 0; i < num;++) {
      cout << x << " \";
      z = x + y;
      x = y;
      y = z;
   }
}

In the main() function, the user inputs a number. The function fib() is called, and the fibonacci series is printed as shown below-

cout << "Enter the number: ";
cin >> num;
cout << "\nThe fibonacci series: ";
fib(num);