C++ Program to Find Fibonacci Numbers using Iteration


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

Example

 Live Demo

#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;
}

Output

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

In the above program, the actual code is present in function fib() to calculate the fibonacci series.

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;
   }
}

In the main() function, a number is entered by the user. The function fib() is called and fibonacci series is printed as follows −

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

Updated on: 26-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements