Write a C# program to find Fibonacci Series

How to write C# program to find the Fibonacci series. An example of a C# program for beginners. Step by step C# code to find the Fibonacci series.

In this example, We will see how to find the Fibonacci series in c#. Before directly dive into code lets understand the problem what is the Fibonacci series.

What is the Fibonacci Series?

A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. Example Fibonacci series is 1, 1, 2, 3, 5, 8, etc.

Steps to find a Fibonacci series

  • First, two numbers always will be (0,1)
  • Now find the sum of the two preceding numbers (0+1=1), (1+1 = 2), (2+1 = 3) and so on.

Now Let’s understand how to find the Fibonacci series in C#

Algorithm to find the Fibonacci series in C#.

  • Define variables (int num1 = 0, num2 = 1, num3, i, number)
  • Read a number to set the limit of series.
  • Execute the loop until the input limit.
  • Print the sum of two predefined numbers(0+1 = 1).
  • Swap the sum (num1 = num2, num2 = num3 )

C# program to find Fibonacci Series

using System;
 
namespace CSharpProgram
{
    class FindFibonaciiSeries
    {
        static void Main(string[] args)
        {
            int num1 = 0, num2 = 1, num3, i, number;
            Console.Write("Enter the number of elements you want to print: ");
            number = int.Parse(Console.ReadLine());
            //prin 0 and 1 manually
            Console.Write(num1 + " " + num2 + " ");
            //Start loop from 2 and execute till the input number-1.
            for (i = 2; i < number; ++i)    
            {
                num3 = num1 + num2;
                Console.Write(num3 + " ");
                num1 = num2;
                num2 = num3;
            }
            
            Console.ReadLine();
        }
    }
}

Output

Enter the number of elements you want to print: 10

0 1 1 2 3 5 8 13 21 34

C# program to find the nth Fibonacci number

find nth Fibonacci number in c#. How to write a C# program to find the nth Fibonacci number. Another Example of Program in c#.

using System;
 
namespace CSharpProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1 = 0, num2 = 1, num3 = 0, i, number;
            Console.Write("Enter the nth number greater than 2: ");
            number = int.Parse(Console.ReadLine());
            for (i = 2; i <= number; ++i)
            {
                num3 = num1 + num2;
                num1 = num2;
                num2 = num3;
            }
            Console.Write(num3 + " ");
            Console.ReadLine();
        }
        
    }
}
 

Output:
Enter the nth number greater than 2: 11
89

 

Add a Comment

Your email address will not be published.

three + 13 =