Skip to content
Home » Programming » C# Program to print out Fibonacci Series.

C# Program to print out Fibonacci Series.

c# Program to print out Fibonacci Series.

In this tutorial, we’ll be doing a C# Program to print Fibonacci Series.

// C# Program to print out Fibonacci Series.
using System;  
  public class Fibonacci
   {  
     static void Main(string[] args)  
      {  
         int x=0,y=1,z,i,number;    
         Console.Write("Upto how many numbers? ");    
         number = int.Parse(Console.ReadLine());  
         Console.Write(x+" "+y+" "); //printing 0 and 1    
         for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed    
         {    
          z=x+y;    
          Console.Write(z+" ");    
          x=y;    
          y=z;    
         }    
      }  
   }

Table of Contents

Output:

Here, the output of fibonacci series in C# programming.

Upto how many numbers? 10
0 1 1 2 3 5 8 13 21 34
Output

Explaination:

We’ve already explained about the basic structure and parameter of C# program so, let’s go through the main program.

int x=0, y=1, z, i, number;

Here, x, y, z, i & number are interger variables. The initial value of x & y is set to 0 and 1 respectively. Variable i is used as loop counter. Similary, number is used for storing the number entered by the user.

Console.Write("Upto how many numbers? ");

This line simply displays a Message written inside the quotation box. Here, we write a message for the user to enter a number of steps to print out Fibonacci Series.

number = int.Parse(Console.ReadLine());

This line just accepts the number (intger value) entered by the user and store it in the inter variable number.

Console.Write(x+" "+y+" ");

This line simply prints 0 and 1.

for(i=2;i<number;++i)
{
z=x+y;
Console.Write(z+" ");
x=y;
y=z;
}

Basically, this block of codes simply runs the loop (number-2) times. Inside each loop, it prints the sum(z) of the last two digits (x and y) & updates value of x by value of y & value of y by value of z.

In this way, the C# program to print out Fibonacci Series.

Also Read: C# Hello World
C# Program to check whether the number is prime or not.
C Sharp for Beginners

Leave a Reply

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