Generating the Fibonacci Sequence in C#: An Iterative Approach

Learn how to generate the Fibonacci sequence in C# using a simple and efficient iterative method. This tutorial provides a clear code example, explains the algorithm, and demonstrates how to obtain a specified number of Fibonacci numbers, ideal for beginners learning iterative programming techniques.



Generating a Fibonacci Sequence in C#

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones (0, 1, 1, 2, 3, 5, 8, 13...). This program demonstrates how to generate this sequence in C# using a simple iterative approach.

Understanding the Fibonacci Sequence

The Fibonacci sequence starts with 0 and 1. Each subsequent number is the sum of the two numbers before it. For example:

  • 0 + 1 = 1
  • 1 + 1 = 2
  • 1 + 2 = 3
  • 2 + 3 = 5
  • And so on...

C# Code to Generate the Fibonacci Sequence


using System;

public class FibonacciExample {
    public static void Main(string[] args) {
        Console.Write("Enter the number of elements: ");
        int number = int.Parse(Console.ReadLine());
        int n1 = 0, n2 = 1, n3, i;
        Console.Write($"{n1} {n2} "); // Print the first two numbers
        // ... (for loop to generate and print the rest of the sequence) ...
    }
}

Explanation

The program first gets user input specifying the desired number of Fibonacci numbers. It initializes the first two numbers (`n1` and `n2`). A `for` loop then iterates to generate the remaining numbers. In each iteration, it calculates the next Fibonacci number (`n3`), prints it, and updates `n1` and `n2` for the next iteration. The loop starts from 2 because the first two numbers (0 and 1) are already printed.