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



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
Updated on: 2020-06-22T10:13:04+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements