Exercise
Function Fibonacci
Objective
Write a C# program that uses recursion to calculate a number in the Fibonacci series (in which the first two items are 1, and for the other elements, each one is the sum of the preceding two).
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Recursive function to calculate the Fibonacci number at a given position
public static int Fibonacci(int n)
{
// Base case: The first and second Fibonacci numbers are 1
if (n == 1 || n == 2)
{
return 1;
}
// Recursive case: The Fibonacci number is the sum of the previous two Fibonacci numbers
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
// Main method where the Fibonacci function is called
public static void Main()
{
// Declare an integer for the position in the Fibonacci series
int position = 6; // Example: We want to calculate the 6th Fibonacci number
// Call the recursive Fibonacci function and print the result
Console.WriteLine("The Fibonacci number at position {0} is: {1}", position, Fibonacci(position));
}
}