.comment-link {margin-left:.6em;}
My Photo
Location: Unspecified, Mauritius

I too, am a bug within Māyā.

My Other Blog(s) and Site(s)
Friend sites and blogs
My Recent Posts
Best Articles
My C-Sharp Ideas
Blog Directories

Monday, October 03, 2005


Arrays in C# and C

[Static Arrays in C and C#]

I never pictured myself writing a tutorial on arrays but here we are - a tutorial on arrays. I'm basically writing this because we just did arrays at uni (C programming language, duh), and a few of my friends came sort of late (and some of them went to the outing) and couldn't understand fuck at all on what the whole deal was about with arrays.

Arrays. I read about arrays when I was 12. It was a Q-Basic tutorial. I still remember, it was saying something like "picture arrays like boxes" ... well anyway, never mind the way you're picturing arrays, let me just start with a small intro on data and arrays.

Please keep in mind that this is a C# blog; the C language and its construct is outside the scope of this blog. However, because I own and maintain this thing, I do pretty much whatever I want with it. You will notice that arrays in C and C# are somewhat similar. Actually, the concept of Arrays remains the same throughout all programming languages. Except ASM and VB. ASM coz you have to write your own shit and deal with it, and VB coz you prolly need to write a poem for the compiler to give you an array. No, well, it's the same in VB too :)


Useful programs need to be fed data to be processed. At some point or the other, it might happen that we need a large amount of the same type of data to hold stuff. Example, if you wanted to hold the salary of 10 employees - you could do something like:

C and C# Code

int Employee1;
int Employee2;
int Employee3;
int Employee4;
int Employee5;
int Employee6;
int Employee7;
int Employee8;
int Employee9;
int Employee10;

But that's not really neat-looking. I mean, what if you had 10,000 employees? Heh, that would sort of suck, wouldn't it? Arrays provide a simpler way of storing large amounts of data. You can declare, in one line:

C Code

int Employees[9];

C# Code

int[] Employees = new int[9];

Declaring an array of of length 9 (int[9] in C# and variableName[9] in C) would be the same as declaring 10 integer elements. Why does an array with accessor [9] have 10 elements? Simple - because an array's elements start with 0.

C and C# Code

Employees[0]; //Employee 1
Employees[1]; //Employee 2
Employees[2]; //Employee 3
Employees[3]; //Employee 4
Employees[4]; //Employee 5
Employees[5]; //Employee 6
Employees[6]; //Employee 7
Employees[7]; //Employee 8
Employees[8]; //Employee 9
Employees[9]; //Employee 10

Assigning Values To Arrays

Assigning a value to an array is pretty simple. We can do this:

C Code

int Employees[4];

Employees[0] = 2400;
Employees[1] = 2100;
Employees[2] = 3050;
Employees[3] = 2400;
Employees[4] = 3380;

C# Code

int[] Employees = new int[4];

Employees[0] = 2400;
Employees[1] = 2100;
Employees[2] = 3050;
Employees[3] = 2400;
Employees[4] = 3380;

There is, however, an easier way of assigning values in an array. Here goes the code:

C Code

int Employees[4] = {2400,2100,3050,2400,3380};

C# Code

int[] Employees = {2400,2100,3050,2400,3380};

Arrays just make the world easier for us. However, behaviour of arrays on C and other programming languages are sort of different. While most modern languages have bounds checking for arrays, C doesn't. For those who have no clue what bounds checking is about - it's just checking whether someone is trying to access an array's elements outside of its specified bounds. You can access the 5th element in an array of 50 items, but you can't access the 1000th element in that same array. In C#, if you try such a thing, an exception will be thrown. In C, nothing will happen - your program will continue to execute, although you'll now have weird garbage data which was used. Example:

C Code

int Employees[4] = {2400,2100,3050,2400,3380};
printf("%d", Employees[50]); //Will Output Garbage Data

C# Code

int[] Employees = {2400,2100,3050,2400,3380};
Console.WriteLine(Employees[50].ToString()); //Will Raise an Exception

While the above C example will run without bitchin' you, C# will give you a System.IndexOutOfRangeException - which is a kind way of saying you fucked up on the array's bounds. C# does check if your code is straying outside the bouds of an array, while C doesn't. It just applies a formula which calculates the memory location of the designated element in the array, reads the memory location, and returns you the result. Voila. You'll have to deal with it by writing proper code, that's all. While dealing with arrays, if you ever end up with garbage data (e.g. an element of array of int returning you -244324 instead of a plain 0), you'll know that you fucked up with the bounds somewhere in your code.

Here's the deal: You can write programs fast in C#, but your programs will consume more processing power, and might eat up more memory space. In C, writing programs is like anal sex, but the programs will run like Beep-Beep with its ass on fire.

Anyway, let's get on with arrays. You can create an array of any type. An array of characters, an array of integers, an array of float - whatever you can think of. The arrays we're discussing here are called "static" arrays. Static arrays have a fixed size (and therefore number of elements). You can't increase the size of the array, nor decrease it. There are several other kinds of arrays in C#, namely dynamic arrays (ArrayLists - hehe) and jagged arrays, but those are outside of the scope of this tutorial.

Multi Dimensional Arrays

What we're going to do now is look at multidimensional arrays. Never mind about the name - Multi Dimensional arrays are just arrays made up of arrays. Let's imagine for a moment that there is a shop which sells Shoes, Hats, and Gloves. We want to represent the number of items sold per day in a grid, as follows:

Mon Tue Wed Thu Fri Sat
Shoes 0 0 1 0 0 2
Hats 2 1 2 2 1 3
Gloves 0 0 0 0 2 1

To store that data, we could:

C Code

int Shoes[5];
int Hats[5];
int Gloves[5];

C# Code

int[] Shoes = new int[5];
int[] Hats = new int[5];
int[] Gloves = new int[5];

or Alternatively:

C Code

int Mon[2];
int Tue[2];
int Wed[2];
int Thu[2];
int Fri[2];
int Sat[2];

C# Code

int[] Mon = new int[2];
int[] Tue = new int[2];
int[] Wed = new int[2];
int[] Thu = new int[2];
int[] Fri = new int[2];
int[] Sat = new int[2];

Shoes[0] would represent the number of shoes sold on Monday, Shoes[1] the number of shoes sold on Tuesday, Gloves[5] the number of gloves sold on Saturday; while on the alternative example, Mon[0] would represent the number of Shoes sold on monday, Mon[1] the number of Hats sold on Monday, Thu[2] the number of Gloves sold on Thursday, and so on. That's not a bad way of doing things. Nowever, if the shop was selling more than 500 items, it would get a little bit difficult to make this work with our current method. Not that it's impossible - but it's not the right way of doing things. This is where multidimensional arrays come into play.

C Code

int ItemsSold[2][5];

C# Code

int[][] ItemsSold = new int[2][5];

The declaration ItemsSold[2][5] in C and int[2][5] in C# is the one of a multidimensional array. Those kinds of arrays allow the user to create arrays of 2, 3, 4 or even N dimensions, according to the needs of the program. Here's a description of how the data is going to be stored in my array:

ItemsSold[0][0]; // Shoes sold on Mon
ItemsSold[0][1]; // Shoes sold on Tue
ItemsSold[0][2]; // Shoes sold on Wed
ItemsSold[0][3]; // Shoes sold on Thu
ItemsSold[0][4]; // Shoes sold on Fri
ItemsSold[0][5]; // Shoes sold on Sat

ItemsSold[1][0]; // Hats sold on Mon
ItemsSold[1][1]; // Hats sold on Tue
ItemsSold[1][2]; // Hats sold on Wed
ItemsSold[1][3]; // Hats sold on Thu
ItemsSold[1][4]; // Hats sold on Fri
ItemsSold[1][5]; // Hats sold on Sat

ItemsSold[2][0]; // Gloves sold on Mon
ItemsSold[2][1]; // Gloves sold on Tue
ItemsSold[2][2]; // Gloves sold on Wed
ItemsSold[2][3]; // Gloves sold on Thu
ItemsSold[2][4]; // Gloves sold on Fri
ItemsSold[2][5]; // Gloves sold on Sat

Well, yes, we could have reversed it all. We could have made a 2-dimensional array which has its first dimension representing the day, and the second dimension representing the item. The code would look like this:

C Code

int ItemsSold[5][2];

C# Code

int[][] ItemsSold = new int[5][2];

The arrys would represent:

ItemsSold[0][0]; // Monday's sales of Shoes
ItemsSold[0][1]; // Monday's sales of Hats
ItemsSold[0][2]; // Monday's sales of Gloves

ItemsSold[1][0]; // Tuesday's sales of Shoes
ItemsSold[1][1]; // Tuesday's sales of Hats
ItemsSold[1][2]; // Tuesday's sales of Gloves

ItemsSold[2][0]; // Wednesday's sales of Shoes
ItemsSold[2][1]; // Wednesday's sales of Hats
ItemsSold[2][2]; // Wednesday's sales of Gloves

ItemsSold[3][0]; // Thursday's sales of Shoes
ItemsSold[3][1]; // Thursday's sales of Hats
ItemsSold[3][2]; // Thursday's sales of Gloves

ItemsSold[4][0]; // Friday's sales of Shoes
ItemsSold[4][1]; // Friday's sales of Hats
ItemsSold[4][2]; // Friday's sales of Gloves

ItemsSold[5][0]; // Saturday's sales of Shoes
ItemsSold[5][1]; // Saturday's sales of Hats
ItemsSold[5][2]; // Saturday's sales of Gloves

Assignment of dimensions is up to you - whether you want to put the days in the first dimension or in the second all depends on you and what you want to code.


Finally, when should we use static arrays, and when should we use dynamic arrays? Static arrays should be used when you're ABSOLUTELY certain that the size of the array will never exceed a certain limit. Example - number of days in a week, number of days in a month (even if it's sometimes 28,29,30 or 31, declaring an array with 31 elements is enough. We might be wasting 4-16 bytes, but it's still ok).

However, we SHOULD use dynamic arrays when we're not certain about the number of elements that is going to fit into the array. E.g. Number of employees, number of files in a directory, number of items being sold by a shop(yes, that can vary).

Dynamic arrays contain additional code to make the whole thing work - which makes it slower. Static arrays are pretty straightforward when it comes to execution - not much code, executes fast.

I hope you enjoyed reading the tutorial :)
I would like to express my warmest thanks to:

  • My 1.5 Gb of Ram, for helping me, all the time
  • My new screen, for not being a blurry dick
  • Michael Jackson, for not reading this tutorial
  • The internet, and TCP/IP for making this possible
  • Notepad, a friend of mine.
  • Bill Gates, for nothing

I'm dedicating this tutorial to my uni friends who are completely clueless about arrays; and to my one and only frequent reader (yeah, I've got only one fucking "frequent" reader. Damn. Thought I was popular.) Ahad. Yo dude! What's up? :P

Shouldnt use arrays. Should use hashtables.
Agreed: Hashtables kick ass; hashing the key to compute the address of the value is pretty useful. However, this tutorial is about arrays, meant for people who don't know what static arrays are about.

But then, there ARE some things which makes the use of an array better - what if you've got two different values with the same keys? Of course, having such a situation would mean bad planning, but in those cases, I'd still recommend arrays. Plus, you can sort arrays ^_-

whhooohooo!!!!va...va...voom...vrrooouum_____Bip-beep....wana a ride>>>get urself seated on a chair and ask your frend to push, push push \push PUSH,,, as we did in the uni saturday>>>>it was really loysihay!:-)
Muhammad Ahad!!!
Yep, my only frequent reader...
My new screen, for not being a blurry dick

So, you would prefer your screen as a clear, in focus dick?

Michael Jackson, for not reading this tutorial

Because Michael Jackson would really be out there, looking for blogs on the C# language.

The internet, and TCP/IP for making this possible

TCP/IP is my friend.

Notepad, a friend of mine

You know Notepad? No way!

Bill Gates, for nothing

Well, I can think of something good that Bill Gates has done for us programmers and those alike; I will let you take the time to ponder what that may be, though.

I know, I am such a smartass, right? Sorry, I couldn't help myself.
*desperately looking for insulting words*
*none found*

Duh. Smartass :)
Did you read my comment on your blog Vittra? I think I put that on an older post of yours - gave you my email in that. It's wonderful to converse through comments on each other's blogs *nodding* but I prefer email.

Was proposing you a link exchange thing - I link up to you, you link up to me :)

Declaring an array of of length 9 (int[9] in C# and variableName[9] in C) would be the same as declaring 10 integer elements.

Idiot, that is wrong. Declaring an int array of length 9 is declaring 9 integer elements, not 10. You access the 9 elements with index 0-8. Go back to basic programming class.
"int Employees[9];"

Dude, that will give your 9 elements, NOT 10.
Learn your programming before writting tutorials.

You have to instanciate 10 elements:
int Employees[10];

That will give you a ranged from 0 to 9 (10 elements)
Ummmm where did you get the idea that say int [] table = new int[9] gives an array of 10 ints etc.

This is completely wrong.

if you did:

int[] table = new int[9];
table[9] = 100;

you would get a 9 int table and throw an IndexOutOfBounds exception!
Sorry, but your C# notation is wrong.
int[] Employees = new int[9];
does NOT declare an array of 10 elements - it declares an array of 9 elements, numbered 0-8.

See the following:
Your code example:

int[] Employees = new int[4];
Employees[0] = 2400;
Employees[1] = 2100;
Employees[2] = 3050;
Employees[3] = 2400;
Employees[4] = 3380;

Would throw an index out of range exception for declaring an array with 4 elements and trying to access the fifth element (index 4). This is in several spots.
Unless they've totally changed arrays in C since I last used it, you've got your index numbering all wrong. The following statement:

int array[5];

creates an array with 5 integer elements that can be referenced as such:

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

In case you don't believe me, I have sources to quote:

If there have been changes to the basic function of C, perhaps you could include the current version number of your compiler in your blog to avoid confusion.
In the section entitled "Assigning Values To Arrays", the defined arrays are given only 4 slices, yet the code examples are assigning 5 elements. Might want to correct that for those who are new to arrays! :)
Post a Comment

Links to this post:

Create a Link

<< Home