How to create Fibonacci series for the given limit using C#

Please find the solution for the same below.




















        

  static void Main(string[] args)
        {
            Fibonacci(10);
        }

        public static void Fibonacci(int limit)
        {
            // Method 1
            int a = 0; int b = 1; int c=0;
            Console.WriteLine("Method 1");
            Console.WriteLine("Fib Series : {0},{1}", a, b);
            for(int i = 2; i < limit; i++)
            {
                c = a + b;
                Console.Write("{0} ",c);
                a = b;
                b = c;

            }

            // Method 2
            int[] fibnArray = new int[limit];
            fibnArray[0] = 0;
            fibnArray[1] = 1;

            for (int i = 2; i < limit; i++)
            {
                fibnArray[i] = fibnArray[i - 2] + fibnArray[i - 1];
            }

            string fib1 = "";
            fibnArray.ToList().ForEach(x => { fib1 = fib1 + x.ToString() + ","; });
            Console.WriteLine("\n Method 2");
            Console.WriteLine("Fibonacci Series " + fib1);

            //Method 3
            Console.WriteLine("Method 3");
            Recurring(0, 1, 1, 10);
            // Method 4
            List fibnList = new List();
            for (int i = 0; i < limit; i++)
            {
                if (i == 0 || i == 1)
                {
                    fibnList.Add(i);
                }
                else
                {
                    fibnList.Add(fibnList[i - 2] + fibnList[i-1]);
                }

            }
            string fib = "";
            fibnList.ForEach(x => { fib = fib + x.ToString() + ","; });
            Console.WriteLine("\n Method 4");
            Console.WriteLine("Fibonacci Series " + fib);
            Console.ReadLine();
        }

        public static void Recurring(int a,int b,int counter,int limit)
        {
            if (counter < limit)
            {
                Console.Write(a);
                int c = a + b;
                counter = counter + 1;
                Recurring(b, c,counter , limit);
            }
                    
        }

0 comments: