How to get the nth value of a Fibonacci series using recursion in C#?

CsharpProgrammingServer Side Programming

Create a method to get the nth value with recursion.

public int displayFibonacci(int n)

Call the method −

displayFibonacci(val)

On calling, the displayFibonacci() meyhod gets called and calculate the nth value using recursion.

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

Let us see the complete code −

Example

 Live Demo

using System;
public class Demo {
   public static void Main(string[] args) {
      Demo d = new Demo();
      int val = 7;
      int res = d.displayFibonacci(val);
      Console.WriteLine("{0}th number in fibonacci series = {1}", val, res);
   }
   public int displayFibonacci(int n) {
      if (n == 0) {
         return 0;
      }  
      if (n == 1) {
         return 1;
      } else {
         return displayFibonacci(n - 1) + displayFibonacci(n - 2);
      }
   }
}

Output

7th number in fibonacci series = 13
raja
Published on 21-Aug-2018 10:02:53
Advertisements