Write a C# function to print nth number in Fibonacci series?


Set the following, if the nth number is let’s say num −

int n = num- 1;
int[] val = new int[n + 1];

Then set the default Fibonacci numbers on the first and second position −

val[0]= 0;
val[1]= 1;

Loop through i=2 to i<=n and find the Fibonacci numbers −

for (int i = 2; i <= n;i++) {
   val[i] = val[i - 2] + val[i - 1];
}

The following is the complete code −

Example

 Live Demo

using System;
public class Demo {
   public static void Main(string[] args) {
      Demo g = new Demo();
      int a = g.displayFibonacci(7);
      Console.WriteLine(a);
   }

   public int displayFibonacci(int num) {
      int n = num- 1;
      int[] val = new int[n + 1];

      val[0]= 0;
      val[1]= 1;

      for (int i = 2; i <= n;i++) {
         val[i] = val[i - 2] + val[i - 1];
      }

      return val[n];

   }
}

Output

8

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements