settingsAccountsettings
Menusettings

Q: Print Fibonacci numbers in C# by given n members of the Fibonacci sequence

+4 votes

Write a program that reads a number n and prints on the console the first n members of the Fibonacci sequence: https://en.wikipedia.org/wiki/Fibonacci_number (at a single line, separated by spaces) : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ….

Examples:

n

output:

1

0

3

0 1 1

10

0 1 1 2 3 5 8 13 21 34

 

asked in C# category by user nikole
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

The task is very interesting :-)

Here is my solution - I wrote a lot of explanations in the comments - so you can read and understand how to solve it...

https://en.wikipedia.org/wiki/Fibonacci_number (Fibonacci number)

using System;

class FibonacciNumbers
{
    static void Main()
    {
        Console.WriteLine("Please enter your number:");
        int n = int.Parse(Console.ReadLine());

        if (n == 0)
        {
            Console.WriteLine("Invalid input!");
            return;//we use return to terminate the program if "n" is 0
        }
        else if (n == 1)
        {
            Console.WriteLine(0);
            return;//we use return to terminate the program if "n" is 1
        }

        int x1 = 0;
        int x2 = 1;
        Console.Write("{0} {1} ", x1, x2);//we print the first 2 numbers of the Fibonacci sequence

        for (int i = 2; i < n; i++)//we do the calculation for the numbers ABOVE 2
        {
            int x3 = x1 + x2;
            Console.Write("{0} ", x3);//we use Console.Write INSTEAD OF Console.WriteLine - to glue the above Console.Write - the start of the Fibonacci
            x1 = x2;
            x2 = x3;
        }
        Console.WriteLine();
    }
}
answered by user ak47seo
edited by user golearnweb
...