Fibonacci in C#

Fibonacci sequence:


1. Basic Iterative Approach:

This is the most straightforward method where we calculate each Fibonacci number iteratively.


using System;


class Program

{

    static void Main()

    {

        Console.Write("Enter the number of terms: ");

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

        int a = 0, b = 1, c;


        Console.WriteLine("Fibonacci Sequence:");

        for (int i = 0; i < n; i++)

        {

            Console.Write(a + " ");

            c = a + b;

            a = b;

            b = c;

        }

    }

}




Output:

Enter the number of terms: 10

Fibonacci Sequence:

0 1 1 2 3 5 8 13 21 34



2. Using yield (Lazy Evaluation)

The second example uses yield to generate Fibonacci numbers lazily. This allows you to generate the Fibonacci sequence without storing all the numbers in memory at once. You simply iterate over the numbers as they are generated.


using System;

using System.Collections.Generic;


public class Program

{

    public static void Main()

    {

        int n = 7;


        // Generate the Fibonacci sequence using LINQ

        var fibonacci = GenerateFibonacci(n);


        // Output the Fibonacci sequence

        foreach (var num in fibonacci)

        {

            Console.WriteLine(num);

        }

    }


    // Optimized Fibonacci method using iteration

    private static IEnumerable<int> GenerateFibonacci(int n)

    {

        int a = 0, b = 1;


        for (int i = 0; i < n; i++)

        {

            yield return a;

            int temp = a;

            a = b;

            b = temp + b;

        }

    }

}




Output:

0

1

1

2

3

5

8



3. Using LINQ to Generate Fibonacci Sequence

In this approach, LINQ is used to create the Fibonacci sequence. It uses Aggregate to build up the Fibonacci sequence in a functional style.


using System;

using System.Linq;

using System.Collections.Generic;


public class Program

{

    public static void Main()

    {

        int n = 7;


        var fibonacci = GenerateFibonacci(n);


        foreach (var num in fibonacci)

        {

            Console.WriteLine(num);

        }

    }


    private static IEnumerable<int> GenerateFibonacci(int n)

    {

        return Enumerable

            .Range(0, n)

            .Select(i => i == 0 ? 0 : i == 1 ? 1 : 0)

            .Aggregate(

                new List<int> { 0, 1 },

                (acc, _) =>

                {

                    var next = acc[acc.Count - 1] + acc[acc.Count - 2];

                    acc.Add(next);

                    return acc;

                })

            .Take(n);

    }

}



Output

0

1

1

2

3

5

8

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced