The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
If you need a specific Fibonacci number or want to know how to calculate it, then here's a simple C# program to generate the Fibonacci sequence up to a specified number of terms:
using System;
class Fibonacci
{
static void Main()
{
Console.Write("Enter the number of terms in the Fibonacci sequence: ");
int terms = int.Parse(Console.ReadLine());
Console.WriteLine("Fibonacci Sequence:");
for (int i = 0; i < terms; i++)
{
Console.Write(FibonacciNumber(i) + " ");
}
}
static int FibonacciNumber(int n)
{
if (n <= 1)
return n;
return FibonacciNumber(n - 1) + FibonacciNumber(n - 2);
}
}
How it works:
- Input: The program prompts the user to enter the number of terms they want in the Fibonacci sequence.
- Fibonacci Calculation: The
FibonacciNumber
method calculates Fibonacci numbers recursively. - Output: The program prints the Fibonacci sequence up to the specified number of terms.
For larger numbers of terms, consider using an iterative approach to improve performance:
static void Main()
{
Console.Write("Enter the number of terms in the Fibonacci sequence: ");
int terms = int.Parse(Console.ReadLine());
Console.WriteLine("Fibonacci Sequence:");
int a = 0, b = 1;
for (int i = 0; i < terms; i++)
{
Console.Write(a + " ");
int temp = a;
a = b;
b = temp + b;
}
}
This iterative
version is more efficient than the Recursive
Approach for larger sequences. The is the Recursive
Approach to calculate the Fibonacci number sequence
Thanks
Tags
csharp