Pages

Thursday, May 9, 2013

C#: Fibonacci Series

//function to display the fibonacci series
public  void  FibonacciSeries(int num)
        {
//set temporary variable
            int fibtemp= 0;
//set the first fibonacci number as 1
            int fib1 =1;
//temporary variable
            int fib2 = 0;
            Console.Write(fib1);
//loop through all the numbers
            for (int i = 0; i < num; i++)
            {
//assign temporary variable
                fib2 = fibtemp;
//save to temporary var
                fibtemp= fib1;
                //   Console.WriteLine(fib1);    
//add both temporary variables         
                fib1 = fib2 + fibtemp;

                Console.Write(" ");
                Console.Write(fib1);   
            }

       }

//input num=20 to display 20 fibonacci number series

Output:
1 1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946

No comments:

Post a Comment