Subscribe to Das Buckleheim

## [C#] Fibonacci Sequence

This is another challenge I did to see if I was capable of completing it without using external resources/references.

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FibonacciSequence
{
class Program
{
static void Main(string[] args)
{
int countTo;
while (true)
{
Console.Write("Please enter how many numbers of the Fibonacci sequence"
+ "\nyou would like to generate (1-47): ");
if (countTo < 1)
{
Console.WriteLine();
Console.WriteLine("Please enter a number of one or more.");
Console.WriteLine();
}
else if (countTo > 47)
{
Console.WriteLine();
Console.WriteLine("Please enter a number of 47 or less.");
Console.WriteLine();
}
else break;
}
Console.WriteLine();
Generate(countTo);
Console.WriteLine();
Console.WriteLine("Press any key to terminate program...");
}

public static void Generate(int input)
{
if (input == 1) Console.WriteLine("0");
else if (input == 2) Console.WriteLine("0, 1");
else
{
int value1 = 0;
int value2 = 1;
int value3;
Console.Write("0, 1, ");
for (int i = 0; i <= input - 4; i++)
{
value3 = value1 + value2;
Console.Write(value3 + ", ");
value1 = value2;
value2 = value3;
}
value3 = value1 + value2;
Console.Write(value3);
}
}
}
}

```

But then I made some improvements to the program; this time I had to look up a few things.

Changes:
-Instead of writing all the numbers on one continuous line, it separates them with new lines
-It can now generate up to 94 numbers rather than 47
-I made the code a bit cleaner
-I added a check in case the input isn't a valid number
-Commas are added to represent thousands, millions, etc.

```using System;
using System.Text;

namespace FibonacciSequence
{
class Program
{
static void Main(string[] args)
{
int countTo;
while (true)
{
Console.Write("Please enter how many numbers of the Fibonacci sequence"
+ "\nyou would like to generate (1-94): ");
{
if (countTo >= 1 && countTo <= 94)
{
break;
}
}
Console.WriteLine("\nInvalid input. Please enter a number between 1 and 94.\n");
}
Console.WriteLine();
Generate(countTo);
Console.WriteLine("\nPress any key to terminate program...");
}

public static void Generate(int input)
{
if (input == 1) Console.WriteLine("0");
else if (input == 2) Console.WriteLine("0\n1");
else
{
ulong value1 = 0;
ulong value2 = 1;
ulong value3;
Console.Write("0\n1\n");
for (int i = 0; i <= input - 4; i++)
{
value3 = value1 + value2;
Console.Write(value3.ToString("#,#" + "\n"));
value1 = value2;
value2 = value3;
}
value3 = value1 + value2;
Console.Write(value3.ToString("#,#" + "\n"));
}
}
}
}

```

### 0 Comments On This Entry

There are no Trackbacks for this entry

S M T W T F S
123456
78910111213
1415161718 19 20
21222324252627
282930