Hi, I haven't used a statically typed language in many years and have set myself the task of getting up to speed with C#. I'm using my usual trick of following the fifteen exercises here http://www.jobsnake.com/seek/articles/index.cgi?openarticle&8533 as my first task.
I've just finished the second Fibonacci task which didn't take to long and works just fine but in my opinion looks ugly and I'm sure could be achieved in far fewer lines of more elegant code.
I usually like to learn by pair programming with someone who already knows what they're doing, but that option isn't open to me today, so I'm hoping posting here will be the next best thing.
So to all the C# Jedi's out there, if you were going to refactor the code below, what would it look like?
using System;
using System.Collections;
namespace Exercises
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Find all fibinacci numbers between:");
int from = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("And:");
int to = Convert.ToInt32(Console.ReadLine());
Fibonacci fibonacci = new Fibonacci();
fibonacci.PrintArrayList(fibonacci.Between(from, to));
}
}
class Fibonacci
{
public ArrayList Between(int from, int to)
{
int last = 1;
int penultimate = 0;
ArrayList results = new ArrayList();
results.Add(penultimate);
results.Add(last);
while(last<to)
{
int fib = last + penultimate;
penultimate = last;
last = fib;
if (fib>from && fib<to) results.Add(fib.ToString());
}
return results;
}
public void PrintArrayList(ArrayList arrayList)
{
Console.WriteLine("Your Fibonacci sequence:");
Console.Write(arrayList[0]);
for(int i = 1; i<arrayList.Count; i++)
{
Console.Write("," + arrayList[i]);
}
Console.WriteLine("");
}
}
}
Regards,
Chris