Fibonacci Series in C#
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. This sequence is widely used in mathematics and computer science.
Understanding the Fibonacci Series
The series starts as:
- 0
- 1
- 1
- 2
- 3
- 5
- 8
- 13
- ...
In C#, we can generate this series using loops or recursion. Below is an example of generating the Fibonacci series using a loop.
Code Example: Fibonacci Series in C#
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter the number of terms for the Fibonacci series:");
int terms = int.Parse(Console.ReadLine());
int first = 0, second = 1, next;
Console.WriteLine("Fibonacci Series:");
Console.Write(first + " " + second + " ");
for (int i = 2; i < terms; i++)
{
next = first + second;
Console.Write(next + " ");
first = second;
second = next;
}
}
}
Explanation
1. The program starts by asking the user to input the number of terms they want to generate.
2. It initializes the first two terms of the Fibonacci series: 0 and 1.
3. A loop is used to calculate the subsequent terms by summing up the previous two terms.
4. The calculated term is printed, and the variables are updated for the next iteration.
Some other examples
Conclusion
The Fibonacci series is a fundamental concept, often used in algorithms and programming challenges. Using this example, you can extend it to explore recursion or dynamic programming approaches.
0 Comments