# Recursion

• 05-02-2008, 09:31 AM
Zosden
Recursion
Here's a sample recursive method for Fibonacci numbers:

Code:

``` public int fibonacci(int n)     {             if(n == 1 || n == 2) // The reason why I did it this way was because I made the recursive call two different ways so I made it                                //clear with the ending statement that there was two different ways this was being called             {                     return 1;             }             else             {                     return fibonacci(n - 1) + fibonacci(n - 2);             }     }```
Here's a sample recursive algorithms to find a N x N board that has N queens on it where no of the queens can attack each other.

Code:

```public void nQueens(int i)     {         if (i == n)         {                 return solution;               }         else         {             for (int k = 0; k < n; k++)             {                 col[i] = k;                 if (isPromising(i))                 {                               nQueens(i+1);                       }             }         }     }         private boolean isPromising(int n)     {         for (int i = 0; i < n; i++)         {             if (col[i] == col[n])                                return false;              if (Math.abs((col[i] - col[n])) == (n - i))                     return false;          }         return true;     }```
• 05-02-2008, 10:20 AM
Eranga
This is simple too pal.

Code:

```        if (n <= 1)             return n;```
• 05-04-2008, 05:54 AM
CaptainMorgan
Eranga, I'm afraid I'm not sure what the point of your post was... care to elaborate?
• 05-05-2008, 03:42 AM
Eranga
Yep, I always try to write more clear codes. Then anyone looking at easy to understand what's going on there.

Do you think it's bad? :)
• 05-05-2008, 05:49 AM
Zosden
The way I posted it was very clear. Since I'm recursively calling it two different ways, I should have to stopping points. The way you tried to edit it isn't has clear because it doesn't tell the reader what values that should stop the call.