Stepbystep create a console c project named Fibonacci Create
Step-by-step:
create a console (c#) project named Fibonacci.
Create a GetFib method that returns an integer array of n Fibonacci number
Signature of the method: public static int[] GetFib(int n).
Following is a simple algorithm that generate n Finonacci from https://www.ics.uci.edu/. I added the comments to explain the logic
int a = 1, b = 1; // first two Finonacci number
// or a = 0, b = 1
for (int i = 3; i <= n; i++) // for the array, i=2 for the third Fibonacci number
{
int c = a + b; // from 3rd number onward, a Fibonacci number is the sum of the preivous 2 numbers.
a = b; // a for the next Fibonacci number
b = c; // b for the next Fibonacci number
}
Use the logic above to get an array of n Finonacci numbers (hint: define an array of size n; assign the value 1 to the first 2 elements of the array; use the for loop to generate and store the rest of the Fthinonacci numbers in the array- no need to update the two previous numbers.
Return the array
In main,
Ask the user how many Fibonacci numbers (n) to generate
Call GetFib(n) to get the array of n Finonacci numbers
Use loop to print the n Fibonacci numbers delimited by “,”
Use try/catch to catch: incorrect format, n < 3 error, and other unexpected runtime errors. Use throw new exception for n < 3 – see Lecture: TryCatch.cs. For unexpected runtime, use a very large n to test it.
Document your code.
Run and test your project. If there are unexpected runtime error, catch them and output a message indicating the type of exception that occurs.
Sample output:
1, 1, 2, 3, 5, 8, 13, 21, …
If 0, 1 are the first two numbers, output will be:
0, 1, 1, 2, 3, 5, 8, 13, 21,
Solution
using System.IO;
using System;
class Program
{
public static int[] GetFib(int n)
{
int[] fib = new int[n]; //array to store the set of foibonacci numbers
int a = 1, b = 1; // first two Finonacci number
fib[0] = 1;
fib[1] = 1;
for (int i = 3; i <= n; i++) // for the array, i=2 for the third Fibonacci number
{
int c = a + b; // from 3rd number onward, a Fibonacci number is the sum of the preivous 2 numbers.
fib[i-1] = c;
a = b; // a for the next Fibonacci number
b = c; // b for the next Fibonacci number
}
return fib;
}
static void Main()
{
Console.WriteLine(\"Enter the fibonacci numbers to be generated :\");
int n = System.Convert.ToInt32(Console.ReadLine());
if(n<3)
{
//throws Exception, when n<3
throw (new FibException(\"n < 3; where n is the number of fibonacci numbers\"));
}
else
{
int[] fib = GetFib(n); // The array containing all the fibonacci numbers are being saved at fib[]
for(int i = 0; i < n; i++)
{
Console.Write(fib[i]+\",\");
}
}
}
}
------------------------------------------------------------------------------------------------
using System;
public class FibException: Exception
{
public FibException(string message) : base(message)
{
}
}

