1. ## Recursion

Here's a sample recursive method for Fibonacci numbers:

Java 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.

Java 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;
}```
Last edited by Zosden; 05-05-2008 at 08:14 AM. Reason: To answer a question  Reply With Quote

2. ## This is simple too pal.

Java Code:
```        if (n <= 1)
return n;```  Reply With Quote

3. ## Eranga, I'm afraid I'm not sure what the point of your post was... care to elaborate?  Reply With Quote

4. ## 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? :)  Reply With Quote

5. ## 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.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•