w3resource

C#: To calculate the Fibonacci number of a specific term

C# Sharp Function: Exercise-12 with Solution

Write a program in C# Sharp to create a recursive function to calculate the Fibonacci number of a specific term.

Visual Presentation:

C# Sharp Exercises: Function : To calculate the Fibonacci number of a specific term

Sample Solution:

C# Sharp Code:

using System;

// Class definition named 'funcexer12'
public class funcexer12
{
    // Method to calculate the Fibonacci number of a specific term using recursion
    public static int Fib(int n1)
    {
        // Base cases: Fibonacci of the 1st and 2nd terms is 1
        if (n1 <= 2)
        {
            return 1;
        }
        else
        {
            // Recursive call: Fibonacci of the nth term is the sum of the (n-1)th and (n-2)th terms
            return Fib(n1 - 1) + Fib(n1 - 2);
        }
    }

    // Main method, the entry point of the program
    public static void Main()
    {
        int num;

        // Display a description of the program
        Console.Write("\n\nRecursive Function : To calculate the Fibonacci number of a specific term :\n");
        Console.Write("-------------------------------------------------------------------------------\n");

        // Prompt the user to input a number
        Console.Write("Enter a number: ");
        num = Convert.ToInt32(Console.ReadLine());

        // Calculate and display the Fibonacci of the given term
        Console.WriteLine("\nThe Fibonacci of {0} th term is {1} \n", num, Fib(num));
    }
}

Sample Output:

Recursive Function : To calculate the Fibonacci number of a specific term :                                   
-------------------------------------------------------------------------------                               
Enter a number: 10                                                                                            
                                                                                                              
The Fibonacci of 10 th term  is 55  

Flowchart :

Flowchart: C# Sharp Exercises - Recursive Function : To calculate the Fibonacci number of a specific term

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to create a function to calculate the sum of the individual digits of a given number.
Next: C# Sharp Recursion Exercises.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.