# Fibonacci Numbers Recursion vs Iteration

I recently was task a Java assignment wich was to create two methods one using recursion(ooh scary…), and the other using a loop to solve the famous Fibonacci numbers. If you don’t know what the Fibonacci Numbers is it’s a series of natural numbers where the next number is equivalent to the sum of previous two numbers. The first two numbers are always 1.

public static int fibonacciRecursion(int nthNumber) {
if (nthNumber == 1 || nthNumber == 2) {
return 1;
}
return fibonacciRecursion(nthNumber — 1) + fibonacciRecursion(nthNumber — 2);
}

And Here is my method using a for loop.

public static int fibonacciLoop(int nthNumber) {
int fibo1 = 1, fibo2 = 1, fibonacci = 1;
for(int i = 3; i <= nthNumber; i++) {
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}

As you can see the recursion way is calling itself and it is much less code than the iterative way, but don’t let that fool you recursion is a complex concept and if you can’t think in “recursive” it can be really difficult to grasp. If you can think in recursive it will make problems like the Fibonacci numbers easier to do, but one huge thing to note is that it is not recommended to use recursion specially in production code. That is why I would always go towards using iteration over recursion.