Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Fibonacci Series in C#
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding numbers. The series typically starts with 0 and 1, producing the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
In C#, there are multiple ways to generate the Fibonacci series, including iterative and recursive approaches.
Using Iterative Approach
The iterative approach uses a loop to calculate each Fibonacci number by adding the two previous numbers −
using System;
public class FibonacciIterative {
public static void Main(string[] args) {
int val1 = 0, val2 = 1, val3, i, n;
n = 8;
Console.WriteLine("Fibonacci series using iterative approach:");
Console.Write(val1 + " " + val2 + " ");
for(i = 2; i < n; i++) {
val3 = val1 + val2;
Console.Write(val3 + " ");
val1 = val2;
val2 = val3;
}
}
}
The output of the above code is −
Fibonacci series using iterative approach: 0 1 1 2 3 5 8 13
Using Recursive Approach
The recursive approach defines a function that calls itself to calculate Fibonacci numbers −
using System;
public class FibonacciRecursive {
public static int Fibonacci(int n) {
if(n <= 1) {
return n;
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
public static void Main(string[] args) {
int n = 8;
Console.WriteLine("Fibonacci series using recursive approach:");
for(int i = 0; i < n; i++) {
Console.Write(Fibonacci(i) + " ");
}
}
}
The output of the above code is −
Fibonacci series using recursive approach: 0 1 1 2 3 5 8 13
Using Array to Store Fibonacci Numbers
You can also store the Fibonacci series in an array for later use −
using System;
public class FibonacciArray {
public static void Main(string[] args) {
int n = 10;
int[] fibonacci = new int[n];
if(n >= 1) fibonacci[0] = 0;
if(n >= 2) fibonacci[1] = 1;
for(int i = 2; i < n; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}
Console.WriteLine("Fibonacci series stored in array:");
for(int i = 0; i < n; i++) {
Console.Write(fibonacci[i] + " ");
}
}
}
The output of the above code is −
Fibonacci series stored in array: 0 1 1 2 3 5 8 13 21 34
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Iterative | O(n) | O(1) | Large numbers, memory-efficient |
| Recursive | O(2^n) | O(n) | Small numbers, easy to understand |
| Array Storage | O(n) | O(n) | When you need to access values multiple times |
Conclusion
The Fibonacci series can be generated in C# using iterative, recursive, or array-based approaches. The iterative method is most efficient for larger sequences, while the recursive approach is simpler to understand but less efficient for large numbers due to repeated calculations.
