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 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

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