C++ → Basics → Input → Arithmetic → Conditions → Loops → Array → Functions → Random Numbers → Fibonacci sequence → Fibonacci sequence using function and if/else condition
The following programs will generate Fibonacci sequence using functions and if else conditions. And after that there is a C++ program that generates first 20 numbers of Fibonacci Sequence, and then separates the even and odd numbers of the sequence. For basics of Fibonacci sequence and generating it using for, while and do-while loop see Basics of Fibonacci Sequence.
Fibonacci Sequence using function and if else conditions
The following C++ program will generate first 10 numbers of Fibonacci sequence using function and if else conditions.
#include <iostream>
using namespace std;
int fib(int n)
{
if (n==1 || n==2)
{
return 1;
}
else
{
int number = fib(n-1) + fib(n-2);
return number;
}
}
int main()
{
for (int i =1; i<11; i++)
{
cout << fib(i) << endl;
}
return 0;
}
Separate the Even and Odd numbers of Fibonacci Sequence
The following C++ program will generate first 20 numbers of Fibonacci Sequence, and then separate the even and odd numbers.
#include <iostream>
using namespace std;
int fib(int n)
{
if (n==1 || n==2)
{
return 1;
}
else
{
int number = fib(n-1) + fib(n-2);
return number;
}
}
int main()
{
for (int i =1; i<21; i++)
{
cout << fib(i) << endl;
}
cout << "The Even Numbers are:" << endl;
for (int j =1; j<21; j++)
{
if (fib(j)%2==0)
{
cout << fib(j) << endl;
}
}
cout << "The Odd Numbers are:" << endl;
for (int k =1; k<21; k++)
{
if (fib(k)%2!=0)
{
cout << fib(k) << endl;
}
}
return 0;
}
NEXT: Classes and Objects