The Fibonacci series is another favourite, especially when it comes to testing if you have ever ran into recursion. If you HAVE run into recursion before, then this would probably have been your first exercise too.
A Fibonacci series is simply the series of numbers in which each number is the sum of the two numbers before it, for instance 1, 1, 2, 3, 5, 8, 13, 21, … and so on.
So without further ado – lets hack out some code!
private static int fibonacci(int i) { if (i==0) return 0; else if (i==1) return 1; return fibonacci(i-1) + fibonacci(i-2); }
There is of course another way to do it, without using recursion – lets take a look
private static int fibonacci(int i) { int result = 1; if (i == 1 || i == 2) return 1; int current = 1; int next = 1; for (int j=3; j <= i; j++) { result = current + next; current = next; next = result; } return result; }
And there we have it. The Fibonacci series two ways. Happy white-boarding.