Saturday, June 30, 2007

Project DaysAndNameOfMonth

This project is one of many codes in the book I am currently reading, Programming in the key of C# by Charles Petzold. It is a really good book which I picked for $20 bucks on amazon. Well my objective here was to simply copy the code from the book into VS. The main reason for this is just to understand what is actuallly going on here with arrays and understanding how they work. I think i have a real good understanding now but I will find out Monday when I have to ask 3 questions regarding this code. Well here now I will post my 3 questions and maybe I will get my answers before then.

1) Why was this done without defining how long the arrays would be?
Ex: string[] astrMonthName, but instead string[12] astrMonthName

I was supposed to have 3 questions but I could only come up with one.

Here is the code:

namespace DaysAndNameOfMonth
{
class DayAndNameOfMonth
{
static void Main(string[] args)
{
string[] astrMonthName = { "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December" };
int[] aiDaysInMonth = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
Console.Write("Enter the month (1 for January... 12 for December): ");
int iMonth = Int32.Parse(Console.ReadLine());
Console.WriteLine("{0} has {1} days.", astrMonthName[iMonth - 1],
aiDaysInMonth[iMonth - 1]);
}
}
}

1 comment:

Lewis Moronta said...

Hey Chris,

In C#, when you define an array of any kind, you define it like this:

int[] x; /* The empty brackets indicate that x is an array of int's */

So in order to tell the compiler how many elements you want in this array, you have to use the "new" operator like this:

x = new int[50];

This will initialize all 50 elements to 0 since values weren't given to each one. One way to init the array would be like this:

x = new int[3] { 3, 2, 1 };

Now element 0 would be equal to 3 and element 2 would be equal to 1. Now since the compiler is smart enough to "see" how many elements you're initiating with, you can leave out the amount of '3' from the brackets like this:

x = new int[] { 3, 2, 1 };

The compiler will still assign 3 elements to x because you initialized it with 3 elements. Simple. Now, there is also a short-hand way to write this, which is like this:

int[] x = { 3, 2, 1};

Also, www.gamedev.net should be bookmarked in your browser. They have awesome resources and they have a 9 week C# workshop starting today.

Click here!

Enjoy!
-Lew