Friday, May 21, 2010

What is the purpose of arrays?

Im currently learning c# : Just have a question.





What is an array, why would you use arrays,how would you know when to use arrays?

What is the purpose of arrays?
well arrays are used to store data of similiar data types
Reply:Store and indexing many data types into just one variable.





(it is not true that the elements can be similar, as well as they can be different types)





For example instead of having:





int var1 = 1;


int var2 = 2;


int var3 = 3;





you have





int[] vars = [1,2,3];





and vars[0] will be 1, vars[1] will be 2 and vars[2] will be 3 (the index is 0 based).
Reply:Arrays are used to store multiple variables of the same type. e.g. if you want to store lottery numbers instead of declaring a bunch of variables you do this:





int[] numbersGenereated = new int[6];





that way you'll have an array of 6 numbers; to access them just do this:





numbersGenerated[1]


numbersGenerated[2] etc
Reply:You should use arrays whenever you have many variables that are related to each other. When programming, arrays are useful because they're like variables you can use a number to reference. Copying and pasting is almost always a sign that you need to use a loop or an array.





Technically, they're also better to use than variables, because it will always store the data consecutively in the memory, leading to more cache hits and much faster access times.


No comments:

Post a Comment