C# program to form the Fibonacci series using recursion
Here's a C# program that forms the Fibonacci series using recursion:
using System;
class Program
{
static void Main()
{
int n = 10;
Console.WriteLine("Fibonacci series up to " + n + ":");
for (int i = 0; i < n; i++)
{
Console.WriteLine(Fibonacci(i));
}
}
static int Fibonacci(int n)
{
// Base case: if n is 0 or 1, return n
if (n == 0 || n == 1)
{
return n;
}
else
{
// Recursive case: calculate the Fibonacci number by summing up
// the previous two Fibonacci numbers (Fibonacci(n - 1) + Fibonacci(n - 2))
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
}
In this program, we have the Fibonacci method that takes an integer n as input and returns the n-th Fibonacci number.
We have a base case where if n is 0 or 1, we directly return n itself, as the Fibonacci sequence starts with 0 and 1.
In the recursive case, we calculate the Fibonacci number by summing up the previous two Fibonacci numbers: Fibonacci(n - 1) (the (n-1)th Fibonacci number) and Fibonacci(n - 2) (the (n-2)th Fibonacci number). We make recursive calls to Fibonacci with the values (n - 1) and (n - 2).
The recursive calls continue until we reach the base case (n equals 0 or 1), at which point the recursion stops and the Fibonacci number is calculated.
In the example above, the output would be:
Fibonacci series up to 10:
0
1
1
2
3
5
8
13
21
34
The Fibonacci series up to 10 is calculated: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.