C++ → Basics → Input → Arithmetic → Conditions → Loops → Array → Functions → Random Numbers → Fibonacci sequence
Generate Fibonacci Numbers in C++ using for, while and do-while loops. Fibonacci sequence starts with 1, 1 and than adds previous two elements. Consider the following first 10 elements of a Fibonacci Sequence. In the end, there is a program that generates first 20 Fibonacci numbers, and also calculate the sum of these numbers.
Fibonacci Sequence: 1 1 2 3 5 8 13 21 34 55 …
Fibonacci Sequence using for loop
The following C++ program will generate first 10 numbers of Fibonacci sequence using for loop.
#include <iostream>
using namespace std;
int main()
{
int first = 1, second = 1, sum;
for (int i =1; i<11; i++)
{
cout << first << endl;
sum = first + second;
first = second;
second = sum;
}
return 0;
}
Fibonacci Sequence using while loop
The following C++ program will generate first 10 numbers of Fibonacci sequence using while loop.
#include <iostream>
using namespace std;
int main()
{
int first = 1, second = 1, sum;
int number = 0;
while (number < 10)
{
cout << first << endl;
sum = first + second;
first = second;
second = sum;
number++;
}
return 0;
}
Fibonacci Sequence using do-while loop
The following C++ program will generate all numbers of Fibonacci sequence below 100 using do-while loop.
#include <iostream>
using namespace std;
int main()
{
int first = 1, second = 1, sum;
do
{
cout << first << endl;
sum = first + second;
first = second;
second = sum;
}
while (first < 100);
return 0;
}
The Sum of the Fibonacci Sequence
The following C++ program will generate first 20 numbers of Fibonacci sequence, and will also calculate the sum of these numbers.
#include <iostream>
using namespace std;
int main()
{
int first = 1, second = 1, sum;
int total = 0;
for (int i =1; i<21; i++)
{
cout << first << endl;
sum = first + second;
first = second;
second = sum;
total = total + first;
}
cout << "The sum is: " << total << endl;
return 0;
}
NEXT: Fibonacci Sequence using function and if else conditions