find the nth fibonacci number in csharp

To find the nth Fibonacci number in C#, there are several approaches. One popular method is to use recursion. Here is an example code for this method:

main.cs
public static int Fibonacci(int n)
{
    if (n <= 1)
    {
        return n;
    }
    else
    {
        return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
}
158 chars
12 lines

In this code, we define a method called Fibonacci that takes an integer n as its input, which represents the nth number in the Fibonacci sequence. If n is less than or equal to 1, we simply return n, because the first and second numbers in the Fibonacci sequence are both equal to 1. Otherwise, we recursively calculate the nth Fibonacci number by calling the Fibonacci method twice, once with n-1 and once with n-2, and adding the results together.

To use this method, you can simply call it with the desired value of n, like this:

main.cs
int result = Fibonacci(10); // returns 55
42 chars
2 lines

gistlibby LogSnag