# Fibonacci Series Using Recursion

## Fibonacci Series Using Recursion

Fibonacci series generates the subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Fibonacci series satisfies the following conditions −

Fn = Fn-1 + Fn-2


Hence, a Fibonacci series can look like this −

F8 = 0 1 1 2 3 5 8 13

or, this −

F8 = 1 1 2 3 5 8 13 21

For illustration purpose, Fibonacci of F8 is displayed as −

## Fibonacci Iterative Algorithm

First we try to draft the iterative algorithm for Fibonacci series.

Procedure Fibonacci(n)
declare f0, f1, fib, loop

set f0 to 0
set f1 to 1

<b>display f0, f1</b>

for loop ← 1 to n

fib ← f0 + f1
f0 ← f1
f1 ← fib

<b>display fib</b>
end for

end procedure


## Fibonacci Recursive Algorithm

Let us learn how to create a recursive algorithm Fibonacci series. The base criteria of recursion.

START
Procedure Fibonacci(n)
declare f0, f1, fib, loop

set f0 to 0
set f1 to 1

display f0, f1

for loop ← 1 to n

fib ← f0 + f1
f0 ← f1
f1 ← fib

display fib
end for

END


## Example

Following are the implementations of the above approach in various programming languages −

#include <stdio.h>
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}
int main() {
int n = 5;
printf("Number is: %d", n);
printf("\nFibonacci series upto number %d are: ", n);
for(int i = 0;i<n;i++) {
printf("%d ",fibbonacci(i));
}
}


### Output

Number is: 5
Fibonacci series upto number 5 are: 0 1 1 2 3

// C++ Code for Fibonacci series
#include <iostream>
using namespace std;
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}
int main() {
int n = 5;
cout<<"Number is: "<<n;
cout << "\nFibbonacci series upto number "<<n<< " are: ";
for(int i = 0;i<n;i++) {
cout << fibbonacci(i) << " ";
}
}


### Output

Number is: 5
Fibbonacci series upto number 5 are: 0 1 1 2 3

// Java Code for Fibonacci series
public class Fibonacci {
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
public static void main(String[] args) {
int n = 5;
System.out.print("Number is: " + n);
System.out.print("\nFibonacci series upto number " + n + ": ");

for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}


### Output

Number is: 5
Fibonacci series upto number 5: 0 1 1 2 3

#Python code for fibonacci Series
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

if __name__ == "__main__":
n = 5
print("Number is ", n)
print("Fibonacci series upto number ",n, "are: ")
for i in range(n):
print(fibonacci(i) , end = " ")


### Output

Number is  5
Fibonacci series upto number  5 are:
0 1 1 2 3