• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Monday, August 10, 2020

Fibonacci Series Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Fibonacci Series Program in C# with some examples. This is one of the most frequently asked C# written interview questions. Please read our previous article where we discussed the Swapping Program with and without using the third variable in C#. As part of this article, we are going to discuss the following pointers.
  1. What is the Fibonacci Series?
  2. What are the different ways to implement the Fibonacci in C#?
  3. How to find the nth Fibonacci number in C#?
  4. How to Print the Fibonacci Series up to a given number in C#?
What is the Fibonacci Series?
The Fibonacci series is nothing but a sequence of numbers in the following order:
Fibonacci Series Program in C# with Examples

The numbers in this series are going to starts with 0 and 1. The next number is the sum of the previous two numbers. The formula for calculating the Fibonacci Series is as follows:

F(n) = F(n-1) + F(n-2) where:
      F(n) is the term number.
      F(n-1) is the previous term (n-1).
      F(n-2) is the term before that (n-2).
What are the different ways to implement the Fibonacci in C#?
In C#, we can print the Fibonacci Series in two ways. They are as follows:
  1. Iterative Approach
  2. Recursion Approach
Iterative Approach to Print Fibonacci Series in C#:
This is the simplest approach and it will print the Fibonacci series by using the length. The following program shows how to use the iterative approach to print the Fibonacci Series in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int firstNumber = 0, SecondNumber = 1, nextNumber, numberOfElements;
            Console.Write("Enter the number of elements to Print : ");
            numberOfElements = int.Parse(Console.ReadLine());
            if(numberOfElements < 2)
            {
                Console.Write("Please Enter a number greater than two");
            }
            else
            {
                //First print first and the second number
                Console.Write(firstNumber + " " + SecondNumber + " ");
                //Starts the loop from 2 because 0 and 1 are already printed
                for(int i = 2; i < numberOfElements; i++)
                {
                    nextNumber = firstNumber + SecondNumber;
                    Console.Write(nextNumber + " ");
                    firstNumber = SecondNumber;
                    SecondNumber = nextNumber;
                }
            }
            
            Console.ReadKey();
        }
    }
}
Output:
Iterative Approach to Print Fibonacci Series in C#

Recursive Approach to Print Fibonacci Series in C#:
In the Recursive Approach, we need to pass the length of the Fibonacci Series to the recursive method and then it will iterate continuously until it reaches the goal. Let us understand this with an example.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Length of the Fibonacci Series : ");
            int number = int.Parse(Console.ReadLine());
            FibonacciSeries(0, 1, 1, number);
            Console.ReadKey();
        }
        public static void FibonacciSeries(int firstNumber, int secondNumber, int counter, int number)
        {
            Console.Write(firstNumber + " ");
            if (counter < number)
            {
                FibonacciSeries(secondNumber, firstNumber + secondNumber, counter + 1, number);
            }
        }
    }
}
Output:
Recursive Approach to Print Fibonacci Series in C#

How to find the nth Fibonacci number in the Fibonacci Series in C#?
It is also possible to print the nth Fibonacci number from the Fibonacci series in C#. The following example prints the nth number from the Fibonacci series.

Using Recursion:
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Nth number of the Fibonacci Series : ");
            int NthNumber = int.Parse(Console.ReadLine());
            //Decrement the Nth Number by 1. This is because the series starts with 0
            NthNumber = NthNumber - 1;
            Console.Write(NthFibonacciNumber(NthNumber));
            Console.ReadKey();
        }
        private static int NthFibonacciNumber(int number)
        {
            if ((number == 0) || (number == 1))
            {
                return number;
            }
            else
            {
                return (NthFibonacciNumber(number - 1) + NthFibonacciNumber(number - 2));
            }
        }
    }
}
Output:
How to find the nth Fibonacci number in the Fibonacci Series using Recursive Function?

You can observe that, in the above implementation, it does a lot of repeated work. So this is a bad implementation to find the nth Fibonacci number in the Fibonacci series. We can avoid this using the iterative approach.

Without Using Recursive Function:

Let us understand how to implement this with an example. Here we are not going to use the Recursive function.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Nth number of the Fibonacci Series : ");
            int NthNumber = int.Parse(Console.ReadLine());
            //Decrement the Nth Number by 1. This is because the series starts with 0
            NthNumber = NthNumber - 1;
            Console.Write(NthFibonacciNumber(NthNumber));
            Console.ReadKey();
        }
        private static int NthFibonacciNumber(int number)
        {
            int firstNumber = 0, secondNumber = 1, nextNumber = 0;
            // To return the first Fibonacci number  
            if (number == 0)
                return firstNumber;
            for (int i = 2; i <= number; i++)
            {
                nextNumber = firstNumber + secondNumber;
                firstNumber = secondNumber;
                secondNumber = nextNumber;
            }
            return secondNumber;
        }
    }
}
Output:
How to find the nth Fibonacci number in the Fibonacci Series without using Recursive Function?

How to Print the Fibonacci Series up to a given number in C#?
Now we will see how to print the Fibonacci up to a given number in C#. Please have a look at the following program.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            int firstNumber = 0, SecondNumber = 1, nextNumber, number;
            Console.Write("Enter the number upto which print the Fibonacci series : ");
            number = int.Parse(Console.ReadLine());
            //First print first and second number
            Console.Write(firstNumber + " " + SecondNumber + " ");
            nextNumber = firstNumber + SecondNumber;
            //Starts the loop from 2 because 0 and 1 are already printed
            for (int i = 2; nextNumber < number; i++)
            {
                Console.Write(nextNumber + " ");
                firstNumber = SecondNumber;
                SecondNumber = nextNumber;
                nextNumber = firstNumber + SecondNumber;
            }
            
            Console.ReadKey();
        }
    }
}
Output:
How to Print the Fibonacci Series up to a given number in C#?

That’s it for today. Here, in this article, I try to explain the Fibonacci Program in C# in different ways. I hope you enjoy this article. In the next article, I am going to discuss the Prime Number Program in C# with some examples.

Summary:
I hope this post will be helpful to write a Fibonacci Series Program in C# with Examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape