Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Fibonacci Series in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

C# is a modern, simple, general-purpose, object-oriented programming language. C# is used to design web apps, desktop apps, mobile apps, games, etc. In this article, we will see the Fibonacci series in C# with examples. 

Fibonacci series in c#

Fibonacci Series Program in C#

The Fibonacci series is a sequence of numbers in the following order:

Two numbers in fibonacci Series

The number will be starting with 0 and 1. The next number is the addition of the previous two numbers in a series. The formula to calculate the Fibonacci series is :

function in C#
F(n) = F(n-1) + F(n-2)  


in which F(n) is the term number

F(n-1) is the previous number
F(n-2) is the number before (n-2)

Example

using System;  
  public class FibonacciExample  
   {  
     public static void Main(string[] args)  
      {  
         int x=0,y=1,z,i,num=10;    
             
         Console.Write(x+" "+y+" "); 
         for(i=2;i<num;++i)   
         {    
          z=x+y;    
          Console.Write(z+" ");    
          x=y;    
          y=z;    
         }    
      }  
   }  

Output:

0 1 1 2 3 5 8 13 21 34 

This program generates the first 10 numbers in the Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) and outputs them to the console. You can change the value of n to generate more or fewer numbers in the series.

The different ways to implement the Fibonacci series in C# are:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

An iterative approach for printing Fibonacci Series in C#

using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int firstNumber = 0, SecondNumber = 1, nextNumber, noOfElements;
            Console.Write("Enter the number of number to Print : ");
            noOfElements = int.Parse(Console.ReadLine());
            if(noOfElements < 2)
            {
                Console.Write(" Enter a digit greater than two");
            }
            else
            {
                //First print the first and the second number
                Console.Write(firstNumber + " " + SecondNumber + " ");
                
                for(int i = 2; i < noOfElements; i++)
                {
                    nextNumber = firstNumber + SecondNumber;
                    Console.Write(nextNumber + " ");
                    firstNumber = SecondNumber;
                    SecondNumber = nextNumber;
                }
            }
            
            Console.ReadKey();
        }
    }
}

Output

Enter the number to Print: 5
0 1 1 2 3 


Time complexity: O(n), as we have used one loop to find the sequence until the given number 

Space Complexity: O(1), Since we are not using any extra space or a recursive call stack, therefore, the space complexity will be equal to O(N).

Recursive Approach to print Fibonacci Series in C#

using System;
namespace LogicalPrograms
{
    public class Fibonacci
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the number to print Fibonacci Series : ");
            int number = int.Parse(Console.ReadLine());
            FibonacciSeries(0, 1, 1, number);
            Console.ReadKey();
        }
        public static void FibonacciSeries(int Number1, int Number2, int counter, int number)
        {
            Console.Write(Number1 + " ");
            if (counter < number)
            {
                FibonacciSeries(Number2, Number1 + Number2, counter + 1, number);
            }
        }
    }
}

Output

Please enter the number to print Fibonacci Series: 5
0 1 1 2 3 


Time complexity: O(n)   as the function takes O(N) time complexity to find the sequence up to a given number.

Space complexity: O(1) due to the space consumed by the recursive call stack as we try to print the sequence upto the given number.
 

Must Read Fibonacci Series in JavaScript

Printing Fibonacci Series in C# without using Recursive Function

using System;
namespace LogicalPrograms
{
    public class Fib
    {
        static void Main(string[] args)
        {
            Console.Write(" Enter Nth number of the Fibonacci Series : ");
            int NthNumber = int.Parse(Console.ReadLine());
            
            NthNumber = NthNumber - 1;
            Console.Write(NthFibonacciNumber(NthNumber));
            Console.ReadKey();
        }
        private static int NthFibonacciNumber(int number)
        {
            int Number1 = 0, Number2 = 1, nextNumber = 0;
            // To return the first Fibonacci number  
            if (number == 0)
                return firstNumber;
            for (int i = 2; i <= number; i++)
            {
                nextNumber = Number1 + Number2;
                Number1 = Number2;
                Number2 = nextNumber;
            }
            return Number2;
        }
    }
}

Output

Enter Nth number of the Fibonacci Series: 5
3


Time complexity: O(n) as we have used single loop to find the sequence until the given number

Space complexity: O(1) Since we are not using any extra variable or a recursive call stack, therefore, the space complexity will be equal to O(N).

Printing the Fibonacci Series in C# upto given number 

using System;
namespace LogicalPrograms
{
    public class Fib1
    {
        static void Main(string[] args)
        {
            int Number1 = 0, Number2 = 1, nextNumber, number;
            Console.Write("Enter the no. upto which print the Fibonacci series : ");
            number = int.Parse(Console.ReadLine());
            
            Console.Write(Number1 + " " + Number2 + " ");
            nextNumber = Number1 + Number2;
            
            for (int i = 2; nextNumber < number; i++)
            {
                Console.Write(nextNumber + " ");
                Number1 = Number2;
                Number2 = nextNumber;
                nextNumber = Number1 + Number2;
            }
            
            Console.ReadKey();
        }
    }
}

Output

Enter the no. upto which print the Fibonacci series: 50
0 1 1 2 3 5 8 13 21 34 


Time complexity: O(n), as we are using single loop for finding Fibonacci upto given number

Space complexity: O(1)  Since we are not using any extra variable or a recursive call stack, therefore, the space complexity will be equal to O(N).

How to find the nth Fibonacci number in the Fibonacci Series in C#?

To find the nth Fibonacci number in the Fibonacci series in C#, you can use either an iterative approach or a recursive approach. Here, I'll demonstrate both methods:

Iterative Approach:

using System;
class Program
{
   static void Main(string[] args)
   {
       // Change 'n' to the desired Fibonacci number position
       int n = 10; 
       int result = FibonacciIterative(n);
       Console.WriteLine($"The {n}th Fibonacci number is: {result}");
   }
   static int FibonacciIterative(int n)
   {
       int a = 0, b = 1, c = 0;
       if (n == 0)
           return a;
       for (int i = 2; i <= n; i++)
       {
           c = a + b;
           a = b;
           b = c;
       }
       return b;
   }
}

 

Recursive Approach:

using System;
class Program
{
   static void Main(string[] args)
   {
       // Change 'n' to the desired Fibonacci number position
       int n = 10; 
       int result = FibonacciRecursive(n);
       Console.WriteLine($"The {n}th Fibonacci number is: {result}");
   }
   static int FibonacciRecursive(int n)
   {
       if (n <= 1)
           return n;
       return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
   }
}

 

Output:

The 10th Fibonacci number is: 55

 

Both methods work to find the nth Fibonacci number. The iterative approach calculates Fibonacci numbers from the bottom up, using a loop to generate successive Fibonacci numbers until it reaches the desired position. The recursive approach breaks down the problem into smaller subproblems, repeatedly calling itself to compute Fibonacci numbers. However, it can be less efficient due to redundant calculations.

Frequently Asked Questions

How to get Fibonacci sequence in C#?

In C#, initialize two variables to 0 and 1, then use a loop to compute and display the next number in the sequence by adding the previous two numbers. Repeat until you achieve the desired number of elements.

What is Fibonacci series algorithm?

The Fibonacci series algorithm begins with 0 and 1 and then adds the last two numbers to produce subsequent numbers. Each number is the sum of the two numbers before it, and the series continues indefinitely.

What is Fibonacci series in C using for loop?

Start with two variables initialized to 0 and 1, then use a for loop to add the two preceding numbers to determine and display the next number in the Fibonacci series in C.

Is there a Fibonacci function in C#?

While there is no built-in Fibonacci algorithm in C#, you can create one. In C#, the Fibonacci sequence can be produced using recursive or iterative functions.

Conclusion

In this blog, we have discussed the Fibonacci series in C# and some approaches to printing the Fibonacci series in c#. We started with the basics of Fibonacci, and then we saw two approaches to printing the Fibonacci series in C# with the help of examples. 

If you want to learn more on such topics, you can see C#methods in C#c# interview questionsc vs c#interface in c#, c# classes and objects, Also, you can visit our website, code studio!

Check out this problem - Check If A String Is Palindrome

You can also refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, Javascriptand System Design.

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Topics covered
1.
Introduction
2.
Fibonacci Series Program in C#
2.1.
Example
3.
An iterative approach for printing Fibonacci Series in C#
3.1.
Output
4.
Recursive Approach to print Fibonacci Series in C#
4.1.
Output
5.
Printing Fibonacci Series in C# without using Recursive Function
5.1.
Output
6.
Printing the Fibonacci Series in C# upto given number 
6.1.
Output
7.
How to find the nth Fibonacci number in the Fibonacci Series in C#?
8.
Frequently Asked Questions
8.1.
How to get Fibonacci sequence in C#?
8.2.
What is Fibonacci series algorithm?
8.3.
What is Fibonacci series in C using for loop?
8.4.
Is there a Fibonacci function in C#?
9.
Conclusion