Write a program in C# to create a function to display the n terms of the Fibonacci sequence.

Answer:

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

namespace Fibonacci
{
    class Program
    {
       
        static void Main(string[] args)
        {
            int n;

            // Taking input for number of terms in Fibonacci sequence
            Console.WriteLine("Enter the number of terms for Fibonacci sequence: ");
            n = Convert.ToInt32(Console.ReadLine());

            // Calling the Fibonacci function
            Fibonacci(n);
        }
        // Function to display the first n terms of the Fibonacci sequence
        static void Fibonacci(int n)
        {
            int a = 0, b = 1, c;

            Console.WriteLine("Fibonacci Sequence:");

            // Display the first n terms
            for (int i = 1; i <= n; i++)
            {
                Console.Write(a + " ");

                // Calculate the next term in the sequence
                c = a + b;
                a = b;
                b = c;
            }
            Console.ReadLine();
        }
    }
}
Scroll to Top