Write a C# Program to Print Fibonacci Series

Do you want to print Fibonacci series in C#? Fibonacci series is a sequence where each number is the sum of the two preceding ones. In this C# tutorial, I will explain to you how to write a C# program to print Fibonacci series.

To write a C# program for printing the Fibonacci series, initialize two integers representing the first two numbers of the series. Use a loop to iterate and calculate subsequent numbers by summing the last two numbers, updating them in each iteration. This approach effectively generates and displays the Fibonacci series up to the desired length specified by the user.

Write a C# Program to Print Fibonacci Series

Let us write a C# program to generate and print the Fibonacci series. In a Fibonacci series, each subsequent number is the sum of the previous two. The series typically starts with 0 and 1. So, the sequence goes like this: 0, 1, 1, 2, 3, 5, 8, 13, and so on.

Here is a simple and efficient way to calculate the Fibonacci series up to a given number of elements in C#.

using System;

class FibonacciSeries
{
    static void Main(string[] args)
    {
        Console.Write("Enter the number of elements: ");
        int elements = Convert.ToInt32(Console.ReadLine());

        int firstNumber = 0, secondNumber = 1, nextNumber, i;

        Console.WriteLine("Fibonacci Series:");
        Console.Write(firstNumber + " " + secondNumber + " ");

        for (i = 2; i < elements; i++)
        {
            nextNumber = firstNumber + secondNumber;
            Console.Write(nextNumber + " ");
            firstNumber = secondNumber;
            secondNumber = nextNumber;
        }
    }
}

Code:

  • Input Request: The program asks the user to input the number of elements in the Fibonacci series they wish to see.
  • Initialization: It starts with two integers, firstNumber, and secondNumber, initialized to 0 and 1, the first two numbers of the series.
  • Looping Logic: A for loop runs from 2 to the number of elements. In each iteration, it calculates the next number by adding the last two numbers and then updates the last two numbers for the next iteration.
  • Output: The program prints each number of the series.

After I ran the code using Visual Studio code, you can see the output in the screenshot below:

Write a C# Program to Print Fibonacci Series

Conclusion

I hope this C# tutorial helps you understand how to write a C# program to print the Fibonacci series. We saw here how to write a C# Program to Print Fibonacci Series.

You may also like: