**Fibonacci Numbers** are sequence numbers called the Fibonacci sequence, and in mathematics, it starts with 0 and 1, and then each number is the sum of the two preceding ones. Fibonacci numbers are strongly related to **Golden Ratio**. In mathematics, two quantities are in the **golden ratio** if their ratio is the same as the ratio of their sum to the larger of two quantities. There is Binet’s formula that shows the *n*th Fibonacci number in terms of *n and* the golden ratio. It implies that the ratio of two consecutive Fibonacci numbers tends to the golden ratio as *n* increases.

Basically, we can say formulate that f_{n} = f_{n-1} + f_{n-2}, for example, we can easily find these Fibonacci Numbers as below;

0+1=1

1+1=2

2+1=3

3+2=5

5+3=8

So we can list these first 20 numbers as 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,…

Fibonacci numbers are something like showing steps of life growing. The golden ratio is also known as a ratio that mostly human likes in nature. So these numbers and ratios are widely used in **art, architecture, music, engineering, nature **also has examples of these. It would be nice to calculate these numbers easily and can be used in one of these areas in your applications.

In programming we can briefly write this Fibonacci function as below;

1 |
next = current + previous; |

We can print out all numbers in range as given **print_fibonacci_numbers(…)** procedure below;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void print_fibonacci_numbers(int N) { int p = 0, f =1, next = 0; std::cout << p << ", " << f << ", "; for (int i = 1; i <= N; ++i) { next = f + p; std::cout << next << ", "; p = f; f = next; } } |

Let’s run this function with C++ Builder in a VCL example ;

- Create a new C++ Builder Console (VCL) Application and modify lines as below

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <vcl.h> #include <windows.h> #include <tchar.h> #include <stdio.h> #include <iostream> void print_fibonacci_numbers(int N) { int p = 0, f =1, next = 0; std::cout << p << ", " << f << ", "; for (int i = 1; i <= N; ++i) { next = f + p; std::cout << next << ", "; p = f; f = next; } } int _tmain(int argc, _TCHAR* argv[]) { print_fibonacci_numbers(20); getchar(); return 0; } |

2. Hit **F9** or press **Run** button to run your codes. That’s All.

Design. Code. Compile. Deploy.

Start Free Trial

Free C++Builder Community Edition