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.cs158 chars12 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.cs42 chars2 lines
gistlibby LogSnag