c-sharp
  1. c-sharp-program-to-display-fibonacci-sequence

Program to Display Fibonacci Sequence - (C# Basic Programs)

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers. In this tutorial, we will discuss a C# program to display the Fibonacci sequence up to a certain number.

Syntax

The syntax for displaying the Fibonacci sequence in C# is as follows:

int n1 = 0, n2 = 1, n3, i, number;
Console.Write("Enter the number of elements: ");
number = int.Parse(Console.ReadLine());
Console.Write(n1 + " " + n2 + " ");
for (i = 2; i < number; i++) {
  n3 = n1 + n2;
  Console.Write(n3 + " ");
  n1 = n2;
  n2 = n3;
}

Example

using System;

namespace FibonacciSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            int n1 = 0, n2 = 1, n3, i, number;

            Console.Write("Enter the number of elements: ");
            number = int.Parse(Console.ReadLine());

            Console.Write(n1 + " " + n2 + " ");  // Printing first two elements

            for (i = 2; i < number; i++)
            {
                n3 = n1 + n2;
                Console.Write(n3 + " ");
                n1 = n2;
                n2 = n3;
            }
        }
    }
}

Output:

Enter the number of elements: 7
0 1 1 2 3 5 8

Explanation

The above program starts from 0 and 1 and calculates the next number in the sequence by adding the previous two numbers. The loop continues until the required number of elements is reached.

Use

Displaying the Fibonacci sequence is a common programming exercise that helps programmers understand loops and conditional statements.

Summary

In this tutorial, we discussed a C# program to display the Fibonacci sequence up to a certain number. We covered the syntax, an example, explanation, use, and summary of the program. By practicing this program, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.

Published on: