In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.
In this example, You’ll see the fibonacci series program in C# using recursion.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp9 { class Program { public static int FindFibonacci(int n) { int p = 0; int q = 1; for (int i = 0; i < n; i++) { int temp = p; p = q; q = temp + q; } return p; } static void Main() { Console.Write(" Input number of terms for the Fibonacci series : "); int n1 = Convert.ToInt32(Console.ReadLine()); Console.Write("\n The Fibonacci series of {0} terms is : ", n1); for (int i = 0; i < n1; i++) { Console.Write("{0} ", FindFibonacci(i)); } Console.ReadKey(); } } } |
Output:
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test { class Program { static long[] numbers; static long Fib(int n) { if (0 == numbers[n]) { numbers[n] = Fib(n - 1) + Fib(n - 2); } return numbers[n]; } static void Main() { Console.Write("n = "); int n = int.Parse(Console.ReadLine()); numbers = new long[n + 2]; numbers[1] = 1; numbers[2] = 1; long result = Fib(n); Console.WriteLine("fib({0}) = {1}", n, result); Console.ReadKey(); } } } |
Output: