Popular Posts

June 14, 2024

C# Program to Print Nth Number in Fibonacci Series Recursive Approach

 

Write a C# Program to Print Nth Number in Fibonacci Series Recursive Approach?

What is Fibonacci Series?

Fibonacci series is a sequence of numbers in below order:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34… The next number is found by adding up the two numbers before it.

The formula for calculating these numbers is:

F(n) = F(n-1) + F(n-2)

where:

F(n) is the term number.
F(n-1) is the previous term (n-1).
F(n-2) is the term before that (n-2).

it starts either with 0 or 1.

Different ways to print Fibonacci Series in C#?

In C#, there are several ways to print Fibonacci Series.
  1. Iterative Approach
  2. Recursion Approach
    Recursive Approach:

    In this approach, We need to pass the length of the Fibonacci Series to the recursive method and then it iterates continuously until it reaches the goal.

    namespace ConsoleApplication
    {
        class Program
        {
            public static int FibonacciSeries(int n)
            {
                if (n == 0) return 0; //To return the first Fibonacci number
                if (n == 1) return 1; //To return the second Fibonacci number
                return FibonacciSeries(n - 1) + FibonacciSeries(n - 2);
            }
            public static void Main(string[] args)
            {
                Console.Write("Enter the length of the Fibonacci Series: ");
                int length = Convert.ToInt32(Console.ReadLine());
                for (int i = 0; i < length; i++)
                {
                    Console.Write("{0} ", FibonacciSeries(i));
                }
                Console.ReadKey();
            }
        }
    }

    Output:

    here's a C# program to print the Nth number in the Fibonacci series using a recursive approach:

    Enter the length of the Fibonacci Series: 12

    0112358 13 21 34 55 89.

    using System;

    class Program
    {
        // Recursive function to calculate the Nth Fibonacci number
        static int Fibonacci(int n)
        {
            if (n <= 1)
                return n;
            return Fibonacci(n - 1) + Fibonacci(n - 2);
        }

        static void Main(string[] args)
        {
            int n = 10; // Change this to get different Fibonacci numbers

            if (n <= 0)
            {
                Console.WriteLine("Invalid input. Please enter a positive integer.");
            }
            else
            {
                Console.WriteLine($"The {n}th number in the Fibonacci series is: {Fibonacci(n)}");
            }
        }
    }

    In this program:

    • The Fibonacci function is a recursive function that calculates the Nth Fibonacci number.
    • In the Main method, you can change the value of n to get the Nth Fibonacci number you desire.
    • The program checks if the input n is a positive integer and prints the Nth Fibonacci number accordingly.

    No comments:
    Write comments