How To Generate The Fibonacci Series In C#

Introduction

In this article, we will learn How To Generate The Fibonacci Series in C#.

The next number is the sum of the previous two numbers which are called the Fibonacci series.

The Fibonacci sequence is a series of numbers starting from 0 and 1.

C# code Example 

Now create a new Console application  and add the code in Program.cs file.

using System;

namespace FibonacciUsingCshap
{
    class Program
    {
        static void Main(string[] args)
        {
            //Fibonacci series 

            int val1 = 0, val2 = 1, val3, i, count;
            Console.WriteLine();
            Console.Write("Enter the number of Elemtnts : ");
            count = int.Parse(Console.ReadLine());
            
            Console.WriteLine("This is Fibonacci series:");
            Console.Write(val1 + " " + val2 + " "); // First 0 and 1 print
            
            for(i = 2; i < count; ++i)
            {
                val3 = val1 + val2; // sum of previous two numbers 
                Console.Write(val3 + " ");
                val1 = val2;
                val2 = val3;
            }
            Console.ReadLine();            
        }
    }
}

Then run your console application.

Enter the number of elements as many Fibonacci series as you  want

Output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories