C++ Program to Find Fibonacci Numbers using Iteration



The term Fibonacci numbers is used in mathematics, which calculates the sum of two preceding numbers that starts from 0 and 1 and continues till based on the given number say num.

Mathemathematically, it is represented by:

Fn = Fn-1 + Fn-2

Let us take an example to understand the above formula based on fibonacci numbers.

F0 = 0 
F1 = 1 
F2 = F1 + F0 = 1 + 0 = 1 
F3 = F2 + F1 = 1 + 1 = 2 
F4 = F3 + F2 = 2 + 1 = 3 
and so on...

In this article, we will learn how to use iteration in fibonacci number in C++.

Example to Use Iteration in Fibonacci Numbers

In this example, we start with two initial variables say x (0) and y(1), and calculate the next term by the sum of two preceeding numbers. Then iterate the series for the fibonacci number through i on num and initialize the sum formula to z to get the expected outcome.

Open Compiler
#include <iostream> using namespace std; void fib(int num) { int x = 0, y = 1; int z = 0; // iterate the series based on num for (int i = 0; i < num; i++) { cout << x << " "; z = x + y; x = y; y = z; } } int main() { int num = 8; // display the fibonacci series cout << "\nThe fibonacci series : " ; fib(num); return 0; }

Output

The above program produces the following result:

The fibonacci series : 0 1 1 2 3 5 8 13 
Updated on: 2025-04-21T18:06:34+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements