Wednesday 19 August 2015

How to generate the Fabonacci Series in C#.Net

Example 1:  


                     We can give the value at the time Runtime.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class fabinacci2
    {
        static void Main()
        {
            int a = -1;
            int b = 1;
            int x;
            Console.WriteLine(" enter the x value ::");
            x = int.Parse(Console.ReadLine());
            for (int i = 0; i < x; i++)
            {
                int sum = b + a;
                a = b;
                b = sum;
                Console.WriteLine(sum);


            }
            Console.ReadLine();
        }
    }
}


OutPut :




Example2 :   fabinacci1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class fabinacci1
    {
        public void fabincc(int x)
        {
            int a = 0;
            int b = 1;
            for (int i = 0; i < x; i++)
            {
                int result = a + b;
                Console.WriteLine(result);
                a = b;
                b = result;
            }
        }
    }
}




Program.cs :   Value can be taken at the time of compilation.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class fabinacci
    {
        static void Main()
        {
            fabinacci1 f = new fabinacci1();
            f.fabincc(10);
            Console.ReadLine();


        }
    }
       


    }

OutPut :



Example 3 : 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class fabonacci
    {
        static void Main()
        {
            Console.WriteLine("ente the value");
            int x = int.Parse(Console.ReadLine());
            for (int i = 0; i < x; i++)
            {
                Console.WriteLine(fabonac(i));
              
            }
            Console.ReadLine();
        }
        static int fabonac(int i)
        {


            if (i <= 0)
            {


                return 0;
            }
            else if (i == 1)
            {
                return 1;
            }
            else
            {
                return fabonac(i - 1) + fabonac(i - 2);
            }


        }
    }
}


Output :

No comments:

Post a Comment