fibonacci sequence c++ recursive function code example
Example 1: fibonacci sequence c++
#include <iostream>
using namespace std;
int main ()
{
int num1, num2, num3, input;
num1 = 0;
num2 = 1;
cout << "How many nums in sequence do you want to see: ";
cin >> input;
cout << num1 << " " << num2 << " ";
for(int i = 2; i < input; i++)
{
num3 = num1 + num2;
cout << num3 << " ";
num1 = num2;
num2 = num3;
}
return 0;
}
Example 2: fibonacci sequence without recursion
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class FibonacciSeriesWithoutRecursion {
public static void main(String args[]) {
fibonacci(10);
}
public static void fibonacci(int number){
for(int i=0; i <= number; i++){
System.out.print(getFibonacci(i) + " ");
}
}
public static int getFibonacci(int n){
if (n == 0) {
return 0;
}
if (n == 1){
return 1;
}
int first = 0;
int second = 1;
int nth = 1;
for (int i = 2; i <= n; i++) {
nth = first + second;
first = second;
second = nth;
}
return nth;
}
}
Output : 0 1 1 2 3 5 8 13 21 34 55