Fibonacci Number Sequence Program in C#

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes like this:

 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...  

If you need a specific Fibonacci number or want to know how to calculate it, then here's a simple C# program to generate the Fibonacci sequence up to a specified number of terms:

 using System;  
 class Fibonacci  
 {  
   static void Main()  
   {  
     Console.Write("Enter the number of terms in the Fibonacci sequence: ");  
     int terms = int.Parse(Console.ReadLine());  
     Console.WriteLine("Fibonacci Sequence:");  
     for (int i = 0; i < terms; i++)  
     {  
       Console.Write(FibonacciNumber(i) + " ");  
     }  
   }  
   static int FibonacciNumber(int n)  
   {  
     if (n <= 1)  
       return n;  
     return FibonacciNumber(n - 1) + FibonacciNumber(n - 2);  
   }  
 }  

How it works:

  1. Input: The program prompts the user to enter the number of terms they want in the Fibonacci sequence.
  2. Fibonacci Calculation: The FibonacciNumber method calculates Fibonacci numbers recursively.
  3. Output: The program prints the Fibonacci sequence up to the specified number of terms.

For larger numbers of terms, consider using an iterative approach to improve performance:

 static void Main()  
 {  
   Console.Write("Enter the number of terms in the Fibonacci sequence: ");  
   int terms = int.Parse(Console.ReadLine());  
   Console.WriteLine("Fibonacci Sequence:");  
   int a = 0, b = 1;  
   for (int i = 0; i < terms; i++)  
   {  
     Console.Write(a + " ");  
     int temp = a;  
     a = b;  
     b = temp + b;  
   }  
 }  

This iterative version is more efficient than the Recursive Approach for larger sequences. The is the Recursive Approach to calculate the Fibonacci number sequence

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال