C# program to find the Fibonacci Sequence using recursion.


In our previous post we have discussed a lot of interesting thing about  Fibonacci Sequence and then implemented the program  to find the Fibonacci Sequence for the terms entered by the user,but the main thing is that we have created that program without recursion and in this post we are going to first take a bird view on recursion and then try to implement the program.So let's start with recursion.

 Recursion:

The simple meaning of recursion is the repeated application of any procedure.And if talk in context of programming then recursion is to call a method repeatedly or use call the function by itself.And we can't say that using of recursive call may always going to improve the performance.It depends on how the recursion call is made.Here in our program we are going to use tail recursive call.

To know more about recursion follow the link : Recursion

Now let us move toward implementing our program using recursion.We are going to make a function named FibonacciFunction() and implement our logic in that function and make a self call.Logic is implemented in a way that if user enter 0 as input he will not get any out put.For 1 he will get 0 as output and for any other input result are calculated accordingly.Below is our final logic to implement Fibonacci Program using recursion in C#.


 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
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static int Main(string[] args)
        {

            int n, i = 0, c;
            Console.WriteLine("Enter the number of terms:");
            n = Convert.ToInt16(Console.ReadLine());

            Console.WriteLine("Fibonacci series\n");
           
            for (c = 1; c <= n; c++)
            {
                int result = FibonacciFunction(i);
                Console.Write(result + " " );
                i++;
            }
            Console.WriteLine();
            return 0;
        }

        public static int FibonacciFunction(int n)
        {
            if (n == 0)
            {
                return 0;
            }
            else if (n == 1)
            {
                return 1;
            }
            else
            {
                return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
            }
        }

    }
}

Output:


Here in this program implementing recursion may not going to improve the performance.

Comments